repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
ZJUGuoShuai/vision
[ "a9940fe4b2b63bd82a2f853616e00fd0bd112f9a", "a9940fe4b2b63bd82a2f853616e00fd0bd112f9a", "a9940fe4b2b63bd82a2f853616e00fd0bd112f9a" ]
[ "torchvision/models/quantization/resnet.py", "test/common_utils.py", "torchvision/__init__.py" ]
[ "from typing import Any, Type, Union, List\n\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\nfrom torch.quantization import fuse_modules\nfrom torchvision.models.resnet import Bottleneck, BasicBlock, ResNet, model_urls\n\nfrom ..._internally_replaced_utils import load_state_dict_from_url\nfrom .utils import _replace_relu, quantize_model\n\n__all__ = [\"QuantizableResNet\", \"resnet18\", \"resnet50\", \"resnext101_32x8d\"]\n\n\nquant_model_urls = {\n \"resnet18_fbgemm\": \"https://download.pytorch.org/models/quantized/resnet18_fbgemm_16fa66dd.pth\",\n \"resnet50_fbgemm\": \"https://download.pytorch.org/models/quantized/resnet50_fbgemm_bf931d71.pth\",\n \"resnext101_32x8d_fbgemm\": \"https://download.pytorch.org/models/quantized/resnext101_32x8_fbgemm_09835ccf.pth\",\n}\n\n\nclass QuantizableBasicBlock(BasicBlock):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super(QuantizableBasicBlock, self).__init__(*args, **kwargs)\n self.add_relu = torch.nn.quantized.FloatFunctional()\n\n def forward(self, x: Tensor) -> Tensor:\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out = self.add_relu.add_relu(out, identity)\n\n return out\n\n def fuse_model(self) -> None:\n torch.quantization.fuse_modules(self, [[\"conv1\", \"bn1\", \"relu\"], [\"conv2\", \"bn2\"]], inplace=True)\n if self.downsample:\n torch.quantization.fuse_modules(self.downsample, [\"0\", \"1\"], inplace=True)\n\n\nclass QuantizableBottleneck(Bottleneck):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super(QuantizableBottleneck, self).__init__(*args, **kwargs)\n self.skip_add_relu = nn.quantized.FloatFunctional()\n self.relu1 = nn.ReLU(inplace=False)\n self.relu2 = nn.ReLU(inplace=False)\n\n def forward(self, x: Tensor) -> Tensor:\n identity = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu2(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n out = self.skip_add_relu.add_relu(out, identity)\n\n return out\n\n def fuse_model(self) -> None:\n fuse_modules(self, [[\"conv1\", \"bn1\", \"relu1\"], [\"conv2\", \"bn2\", \"relu2\"], [\"conv3\", \"bn3\"]], inplace=True)\n if self.downsample:\n torch.quantization.fuse_modules(self.downsample, [\"0\", \"1\"], inplace=True)\n\n\nclass QuantizableResNet(ResNet):\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super(QuantizableResNet, self).__init__(*args, **kwargs)\n\n self.quant = torch.quantization.QuantStub()\n self.dequant = torch.quantization.DeQuantStub()\n\n def forward(self, x: Tensor) -> Tensor:\n x = self.quant(x)\n # Ensure scriptability\n # super(QuantizableResNet,self).forward(x)\n # is not scriptable\n x = self._forward_impl(x)\n x = self.dequant(x)\n return x\n\n def fuse_model(self) -> None:\n r\"\"\"Fuse conv/bn/relu modules in resnet models\n\n Fuse conv+bn+relu/ Conv+relu/conv+Bn modules to prepare for quantization.\n Model is modified in place. Note that this operation does not change numerics\n and the model after modification is in floating point\n \"\"\"\n\n fuse_modules(self, [\"conv1\", \"bn1\", \"relu\"], inplace=True)\n for m in self.modules():\n if type(m) == QuantizableBottleneck or type(m) == QuantizableBasicBlock:\n m.fuse_model()\n\n\ndef _resnet(\n arch: str,\n block: Type[Union[BasicBlock, Bottleneck]],\n layers: List[int],\n pretrained: bool,\n progress: bool,\n quantize: bool,\n **kwargs: Any,\n) -> QuantizableResNet:\n\n model = QuantizableResNet(block, layers, **kwargs)\n _replace_relu(model)\n if quantize:\n # TODO use pretrained as a string to specify the backend\n backend = \"fbgemm\"\n quantize_model(model, backend)\n else:\n assert pretrained in [True, False]\n\n if pretrained:\n if quantize:\n model_url = quant_model_urls[arch + \"_\" + backend]\n else:\n model_url = model_urls[arch]\n\n state_dict = load_state_dict_from_url(model_url, progress=progress)\n\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet18(\n pretrained: bool = False,\n progress: bool = True,\n quantize: bool = False,\n **kwargs: Any,\n) -> QuantizableResNet:\n r\"\"\"ResNet-18 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n quantize (bool): If True, return a quantized version of the model\n \"\"\"\n return _resnet(\"resnet18\", QuantizableBasicBlock, [2, 2, 2, 2], pretrained, progress, quantize, **kwargs)\n\n\ndef resnet50(\n pretrained: bool = False,\n progress: bool = True,\n quantize: bool = False,\n **kwargs: Any,\n) -> QuantizableResNet:\n\n r\"\"\"ResNet-50 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n quantize (bool): If True, return a quantized version of the model\n \"\"\"\n return _resnet(\"resnet50\", QuantizableBottleneck, [3, 4, 6, 3], pretrained, progress, quantize, **kwargs)\n\n\ndef resnext101_32x8d(\n pretrained: bool = False,\n progress: bool = True,\n quantize: bool = False,\n **kwargs: Any,\n) -> QuantizableResNet:\n r\"\"\"ResNeXt-101 32x8d model from\n `\"Aggregated Residual Transformation for Deep Neural Networks\" <https://arxiv.org/pdf/1611.05431.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n quantize (bool): If True, return a quantized version of the model\n \"\"\"\n kwargs[\"groups\"] = 32\n kwargs[\"width_per_group\"] = 8\n return _resnet(\"resnext101_32x8d\", QuantizableBottleneck, [3, 4, 23, 3], pretrained, progress, quantize, **kwargs)\n", "import contextlib\nimport functools\nimport os\nimport random\nimport shutil\nimport tempfile\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torchvision import io\n\nimport __main__ # noqa: 401\n\n\nIN_CIRCLE_CI = os.getenv(\"CIRCLECI\", False) == \"true\"\nIN_RE_WORKER = os.environ.get(\"INSIDE_RE_WORKER\") is not None\nIN_FBCODE = os.environ.get(\"IN_FBCODE_TORCHVISION\") == \"1\"\nCUDA_NOT_AVAILABLE_MSG = \"CUDA device not available\"\nCIRCLECI_GPU_NO_CUDA_MSG = \"We're in a CircleCI GPU machine, and this test doesn't need cuda.\"\n\n\[email protected]\ndef get_tmp_dir(src=None, **kwargs):\n tmp_dir = tempfile.mkdtemp(**kwargs)\n if src is not None:\n os.rmdir(tmp_dir)\n shutil.copytree(src, tmp_dir)\n try:\n yield tmp_dir\n finally:\n shutil.rmtree(tmp_dir)\n\n\ndef set_rng_seed(seed):\n torch.manual_seed(seed)\n random.seed(seed)\n\n\nclass MapNestedTensorObjectImpl(object):\n def __init__(self, tensor_map_fn):\n self.tensor_map_fn = tensor_map_fn\n\n def __call__(self, object):\n if isinstance(object, torch.Tensor):\n return self.tensor_map_fn(object)\n\n elif isinstance(object, dict):\n mapped_dict = {}\n for key, value in object.items():\n mapped_dict[self(key)] = self(value)\n return mapped_dict\n\n elif isinstance(object, (list, tuple)):\n mapped_iter = []\n for iter in object:\n mapped_iter.append(self(iter))\n return mapped_iter if not isinstance(object, tuple) else tuple(mapped_iter)\n\n else:\n return object\n\n\ndef map_nested_tensor_object(object, tensor_map_fn):\n impl = MapNestedTensorObjectImpl(tensor_map_fn)\n return impl(object)\n\n\ndef is_iterable(obj):\n try:\n iter(obj)\n return True\n except TypeError:\n return False\n\n\[email protected]\ndef freeze_rng_state():\n rng_state = torch.get_rng_state()\n if torch.cuda.is_available():\n cuda_rng_state = torch.cuda.get_rng_state()\n yield\n if torch.cuda.is_available():\n torch.cuda.set_rng_state(cuda_rng_state)\n torch.set_rng_state(rng_state)\n\n\ndef cycle_over(objs):\n for idx, obj1 in enumerate(objs):\n for obj2 in objs[:idx] + objs[idx + 1 :]:\n yield obj1, obj2\n\n\ndef int_dtypes():\n return (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)\n\n\ndef float_dtypes():\n return (torch.float32, torch.float64)\n\n\[email protected]\ndef disable_console_output():\n with contextlib.ExitStack() as stack, open(os.devnull, \"w\") as devnull:\n stack.enter_context(contextlib.redirect_stdout(devnull))\n stack.enter_context(contextlib.redirect_stderr(devnull))\n yield\n\n\ndef cpu_and_gpu():\n import pytest # noqa\n\n return (\"cpu\", pytest.param(\"cuda\", marks=pytest.mark.needs_cuda))\n\n\ndef needs_cuda(test_func):\n import pytest # noqa\n\n return pytest.mark.needs_cuda(test_func)\n\n\ndef _create_data(height=3, width=3, channels=3, device=\"cpu\"):\n # TODO: When all relevant tests are ported to pytest, turn this into a module-level fixture\n tensor = torch.randint(0, 256, (channels, height, width), dtype=torch.uint8, device=device)\n data = tensor.permute(1, 2, 0).contiguous().cpu().numpy()\n mode = \"RGB\"\n if channels == 1:\n mode = \"L\"\n data = data[..., 0]\n pil_img = Image.fromarray(data, mode=mode)\n return tensor, pil_img\n\n\ndef _create_data_batch(height=3, width=3, channels=3, num_samples=4, device=\"cpu\"):\n # TODO: When all relevant tests are ported to pytest, turn this into a module-level fixture\n batch_tensor = torch.randint(0, 256, (num_samples, channels, height, width), dtype=torch.uint8, device=device)\n return batch_tensor\n\n\nassert_equal = functools.partial(torch.testing.assert_close, rtol=0, atol=1e-6)\n\n\ndef get_list_of_videos(tmpdir, num_videos=5, sizes=None, fps=None):\n names = []\n for i in range(num_videos):\n if sizes is None:\n size = 5 * (i + 1)\n else:\n size = sizes[i]\n if fps is None:\n f = 5\n else:\n f = fps[i]\n data = torch.randint(0, 256, (size, 300, 400, 3), dtype=torch.uint8)\n name = os.path.join(tmpdir, \"{}.mp4\".format(i))\n names.append(name)\n io.write_video(name, data, fps=f)\n\n return names\n\n\ndef _assert_equal_tensor_to_pil(tensor, pil_image, msg=None):\n np_pil_image = np.array(pil_image)\n if np_pil_image.ndim == 2:\n np_pil_image = np_pil_image[:, :, None]\n pil_tensor = torch.as_tensor(np_pil_image.transpose((2, 0, 1)))\n if msg is None:\n msg = \"tensor:\\n{} \\ndid not equal PIL tensor:\\n{}\".format(tensor, pil_tensor)\n assert_equal(tensor.cpu(), pil_tensor, msg=msg)\n\n\ndef _assert_approx_equal_tensor_to_pil(\n tensor, pil_image, tol=1e-5, msg=None, agg_method=\"mean\", allowed_percentage_diff=None\n):\n # TODO: we could just merge this into _assert_equal_tensor_to_pil\n np_pil_image = np.array(pil_image)\n if np_pil_image.ndim == 2:\n np_pil_image = np_pil_image[:, :, None]\n pil_tensor = torch.as_tensor(np_pil_image.transpose((2, 0, 1))).to(tensor)\n\n if allowed_percentage_diff is not None:\n # Assert that less than a given %age of pixels are different\n assert (tensor != pil_tensor).to(torch.float).mean() <= allowed_percentage_diff\n\n # error value can be mean absolute error, max abs error\n # Convert to float to avoid underflow when computing absolute difference\n tensor = tensor.to(torch.float)\n pil_tensor = pil_tensor.to(torch.float)\n err = getattr(torch, agg_method)(torch.abs(tensor - pil_tensor)).item()\n assert err < tol\n\n\ndef _test_fn_on_batch(batch_tensors, fn, scripted_fn_atol=1e-8, **fn_kwargs):\n transformed_batch = fn(batch_tensors, **fn_kwargs)\n for i in range(len(batch_tensors)):\n img_tensor = batch_tensors[i, ...]\n transformed_img = fn(img_tensor, **fn_kwargs)\n assert_equal(transformed_img, transformed_batch[i, ...])\n\n if scripted_fn_atol >= 0:\n scripted_fn = torch.jit.script(fn)\n # scriptable function test\n s_transformed_batch = scripted_fn(batch_tensors, **fn_kwargs)\n torch.testing.assert_close(transformed_batch, s_transformed_batch, rtol=1e-5, atol=scripted_fn_atol)\n", "import os\nimport warnings\n\nimport torch\nfrom torchvision import datasets\nfrom torchvision import io\nfrom torchvision import models\nfrom torchvision import ops\nfrom torchvision import transforms\nfrom torchvision import utils\n\nfrom .extension import _HAS_OPS\n\ntry:\n from .version import __version__ # noqa: F401\nexcept ImportError:\n pass\n\n# Check if torchvision is being imported within the root folder\nif not _HAS_OPS and os.path.dirname(os.path.realpath(__file__)) == os.path.join(\n os.path.realpath(os.getcwd()), \"torchvision\"\n):\n message = (\n \"You are importing torchvision within its own root folder ({}). \"\n \"This is not expected to work and may give errors. Please exit the \"\n \"torchvision project source and relaunch your python interpreter.\"\n )\n warnings.warn(message.format(os.getcwd()))\n\n_image_backend = \"PIL\"\n\n_video_backend = \"pyav\"\n\n\ndef set_image_backend(backend):\n \"\"\"\n Specifies the package used to load images.\n\n Args:\n backend (string): Name of the image backend. one of {'PIL', 'accimage'}.\n The :mod:`accimage` package uses the Intel IPP library. It is\n generally faster than PIL, but does not support as many operations.\n \"\"\"\n global _image_backend\n if backend not in [\"PIL\", \"accimage\"]:\n raise ValueError(\"Invalid backend '{}'. Options are 'PIL' and 'accimage'\".format(backend))\n _image_backend = backend\n\n\ndef get_image_backend():\n \"\"\"\n Gets the name of the package used to load images\n \"\"\"\n return _image_backend\n\n\ndef set_video_backend(backend):\n \"\"\"\n Specifies the package used to decode videos.\n\n Args:\n backend (string): Name of the video backend. one of {'pyav', 'video_reader'}.\n The :mod:`pyav` package uses the 3rd party PyAv library. It is a Pythonic\n binding for the FFmpeg libraries.\n The :mod:`video_reader` package includes a native C++ implementation on\n top of FFMPEG libraries, and a python API of TorchScript custom operator.\n It generally decodes faster than :mod:`pyav`, but is perhaps less robust.\n\n .. note::\n Building with FFMPEG is disabled by default in the latest `main`. If you want to use the 'video_reader'\n backend, please compile torchvision from source.\n \"\"\"\n global _video_backend\n if backend not in [\"pyav\", \"video_reader\"]:\n raise ValueError(\"Invalid video backend '%s'. Options are 'pyav' and 'video_reader'\" % backend)\n if backend == \"video_reader\" and not io._HAS_VIDEO_OPT:\n message = \"video_reader video backend is not available.\" \" Please compile torchvision from source and try again\"\n warnings.warn(message)\n else:\n _video_backend = backend\n\n\ndef get_video_backend():\n \"\"\"\n Returns the currently active video backend used to decode videos.\n\n Returns:\n str: Name of the video backend. one of {'pyav', 'video_reader'}.\n \"\"\"\n\n return _video_backend\n\n\ndef _is_tracing():\n return torch._C._get_tracing_state()\n" ]
[ [ "torch.quantization.fuse_modules", "torch.quantization.DeQuantStub", "torch.nn.ReLU", "torch.nn.quantized.FloatFunctional", "torch.quantization.QuantStub" ], [ "torch.set_rng_state", "torch.jit.script", "torch.abs", "torch.randint", "torch.manual_seed", "torch.get_rng_state", "torch.cuda.is_available", "torch.cuda.get_rng_state", "numpy.array", "torch.cuda.set_rng_state", "torch.testing.assert_close" ], [ "torch._C._get_tracing_state" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jonathanyepez/Master-C3
[ "37a3a13ef2bc8f51d3da3ca1b3704569ef83ef3d" ]
[ "CasoPractico01.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 6 18:03:09 2020\r\n\r\n@author: Jonathan A. Yepez M.\r\n\"\"\"\r\n\r\n#Task Description\r\n\"\"\"\r\nEn el archivo auto.csv se encuentran los siguientes datos de diferentes automoviles:\r\n * Cilindros\r\n * Cilindrada\r\n * Potencia\r\n * Peso\r\n * Aceleracion\r\n * Año del coche\r\n * Origen\r\n * Consumo (mpg)\r\n \r\nLas unidades de las características no se encuentran en el sistema internacional.\r\nLa variable 'origen' es un código que identifica el país de orígen.\r\n\r\nTASK: Crear un modelo para que se pueda estimar el consumo de un vehículo a partir del resto de las variables\r\n\"\"\"\r\n#Import the libraries that will be used in this case\r\nimport pandas as pd\r\nfrom pandas.plotting import scatter_matrix #for a specific stage in EDA\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import mean_squared_error\r\nimport seaborn as sns #visualisation\r\nimport matplotlib.pyplot as plt #visualisation\r\n\r\n#Read the data and create a dataframe\r\ndf = pd.read_csv(\"auto.csv\")\r\nprint(\"--------------------\")\r\nprint(df.info()) #a quick view of the dataframe structure\r\nprint(\"--------------------\")\r\nprint(df.describe()) #a more in-depth description of the information contained in the df\r\nprint(\"--------------------\")\r\nprint(df.head()) #show the first 5 entries of the dataframe\r\nprint(\"the columns for this dataframe are:\")\r\nprint(df.columns)\r\n\r\n#we check for missing values (NAs)\r\n#print(df.isnull().sum())\r\nif(df.isnull().sum().sum()== 0):\r\n print(\"\\nThere are NO missing values.\\n\")\r\nelse:\r\n print(\"\\nThere are\",df.isnull().sum().sum(),\"missing values in the dataframe!\\n\")\r\n\r\n#EDA => Exploratory Data Analysis\r\ndf = df.drop_duplicates() #remove duplicates (if applicable)\r\n\r\n#Scatter matrix for the whole data\r\nscatter_matrix(df, figsize = (12, 12), diagonal = 'kde');\r\n\r\nplt.figure(figsize=(10, 6)) #size configuration for plotting\r\nsns.distplot(df['mpg'], color='b', hist_kws={'alpha': 0.4}); #we first generate a distribution plot for 'mpg'\r\n#Se nota una tendencia a un consumo entre 20 y 30 mpgs dentro del dataset.\r\n\r\ndf_cont = df.select_dtypes(include = ['float64']) #we select the continuous variables \r\nprint(\"The continuous variables for this case are: \\n\")\r\nprint(df_cont.head())\r\n\r\n#Analysing the continuous variables -> scatter plots\r\nfor i in range(len(df_cont.columns)-1):\r\n sns.pairplot(data=df_cont, x_vars=df_cont.columns[i], y_vars=['mpg'], height = 5, aspect=2) #scatter plot vars vs 'mpg'\r\n\r\n\"\"\"\r\nEn este caso, notamos una relación inversamente proporcional entre el consumo (mpg) y las\r\nvariables displacement, horsepower, y weight. Esto nos indica que a mayor potencia y \r\ndesplazamiento (en términos del motor), el consumo de gasolina será mayor y por ende se\r\ntendrá un menor 'rendimiento' de mpg.\r\nEn el caso de la variable acceleration, se nota un grafico de dispersión sin una tendencia\r\nclara. Esto puede deberse a que esta característica varía entre modelos y tipos de carro\r\ncasi intependientemente del consumo de gasolina.\r\n\"\"\"\r\n \r\ndf_cat = df.select_dtypes(include = ['int64']) #we select the 'categorical' variables.\r\nprint(\"\\nThe categorical variables for this case are: \\n\")\r\nprint(df_cat.head())\r\n\r\nfor i in range(len(df_cat.columns)):\r\n sns.catplot(x=df_cat.columns[i], y=\"mpg\", data=df, alpha=0.5) #gnerate a catplot\r\n ax = sns.boxplot(x=df_cat.columns[i], y=\"mpg\", data=df) #add a boxplot on top of the catplot\r\n plt.setp(ax.artists, alpha=0.6, edgecolor=\"k\")\r\n\r\n\"\"\"\r\nTras haber presentado las gráficas para las variables categóricas, se nota que el número \r\nde cilindros muestra cierta tendencia en términos generales. A grosso modo, se puede asumir\r\nque cuando un vehículo tiene 8 cilindros, el rendimiento en mpg tiende a ser notablemente \r\nmenor a uno que tenga 4 cilindros.\r\nAsi mismo, el origen del vehículo indica que, si bien es cierto no hay una variación extrema, \r\nse puede asumir que aquellos provenientes del país '3', tienen un mejor consumo de \r\ngasolina.\r\nEn el caso del año de fabricación (model_year), se observa una tendencia general a la mejora\r\nde mpg conforme se avanza en el tiempo. Esto puede deberse a los avances en el área de la\r\nmecánica automotriz y la implementación de mejores diseños a nivel de componentes mecánicos\r\ncomo aerodinámicos.\r\n\"\"\"\r\n\r\n#Implementing the Regression Model\r\nindep_vars = df.iloc[:,:-1] #selecting 'independent variables'\r\ndep_var = df[[\"mpg\"]] #selecting the 'dependent variable'\r\n\r\n#separating the data into train and test sets\r\nx_train, x_test, y_train, y_test = train_test_split(indep_vars,dep_var)\r\n\r\nmodel = LinearRegression() #constructor that initializes a LinearRegression object\r\n\r\nmodel.fit(x_train, y_train) #fit the model using the training set\r\n\r\npred_train = model.predict(x_train) #prediction based on the training set\r\npred_test = model.predict(x_test) #prediction based on the test set\r\n\r\n#Checking results using R^2 and MSE\r\nprint(\"====================\\n\")\r\nprint('\\nR2 en entrenamiento es: ', round(model.score(x_train, y_train),4))\r\nprint('MSE en entrenamiento: ', round(mean_squared_error(y_train, pred_train),2)) \r\nprint(\"-----------------------\")\r\nprint('R2 en validación es: ', round(model.score(x_test, y_test),4))\r\nprint('MSE en validación es: ', round(mean_squared_error(y_test, pred_test),2))\r\n\r\n\"\"\"\r\nSe ha obtenido resultados aceptables en terminos de precisión. Dado que los valores de MSE\r\ny R^2 en los test y train sets son similares se puede determinar que no se presenta\r\noverfitting. \r\nLos parametros de la regresión se muestran a continuación \r\n\"\"\"\r\n\r\nprint(\"====================\\n\")\r\nprint(\"Los parametros de la regresion son: \")\r\nprint(model.coef_)\r\nprint(\"El termino independiente de la regresión es: \", model.intercept_)" ]
[ [ "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.metrics.mean_squared_error", "matplotlib.pyplot.setp", "sklearn.linear_model.LinearRegression", "pandas.plotting.scatter_matrix", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
meltmedia/the-ark
[ "d559897494e02a2e2048fdc44014f17af89691bb" ]
[ "the_ark/screen_capture.py" ]
[ "import math\nimport numpy\nfrom PIL import Image\nfrom the_ark.selenium_helpers import SeleniumHelperExceptions, ElementNotVisibleError, ElementError\nfrom StringIO import StringIO\nimport time\nimport traceback\n\nDEFAULT_SCROLL_PADDING = 100\nSCREENSHOT_FILE_EXTENSION = \"png\"\nDEFAULT_PIXEL_MATCH_OFFSET = 100\nFIREFOX_HEAD_HEIGHT = 75\nMAX_IMAGE_HEIGHT = 32768.0\n\n\nclass Screenshot:\n \"\"\"\n A helper class for taking screenshots using a Selenium Helper instance\n \"\"\"\n def __init__(self, selenium_helper, paginated=False, header_ids=None, footer_ids=None,\n scroll_padding=DEFAULT_SCROLL_PADDING, pixel_match_offset=DEFAULT_PIXEL_MATCH_OFFSET,\n file_extenson=SCREENSHOT_FILE_EXTENSION, resize_delay=0, content_container_selector=\"html\"):\n \"\"\"\n Initializes the Screenshot class. These variable will be used throughout to help determine how to capture pages\n for this website.\n :param\n - selenium_helper: SeleniumHelper() - The Selenium Helper object whose browser you are capturing\n - paginated: bool - if True, all full page screenshots captured by this class will be a sequence of\n viewport sized images\n - header_ids: list - A list of css_selectors for elements that \"stick\" to the top of the screen when\n scrolling. These hidden and shown while capturing the screen so that they display\n only at the top of the page, and do not cover any content\n - footer_ids: list - A list of css_selectors for elements that \"stick\" to the bottom of the screen\n when scrolling. These hidden and shown while capturing the screen so that they\n display only at the bottom of the page, and do not cover any content\n - scroll_padding: int - The height, in pixels, of the overlap between paginated captures. This is also\n used when scrolling elements. the element is scrolled its height minus the padding\n to create an overlapping of content shown on both images to not cut any text in half\n - file_extenson: string - If provided, this extension will be used while creating the image. This must\n be an extension that is usable with PIL\n \"\"\"\n # Set parameters as class variables\n self.sh = selenium_helper\n self.paginated = paginated\n self.headers = header_ids\n self.footers = footer_ids\n self.content_container_selector = content_container_selector\n self.scroll_padding = scroll_padding\n self.pixel_match_offset = pixel_match_offset\n self.file_extenson = \"png\"\n\n self.headless = self.sh.desired_capabilities.get(\"headless\", False)\n self.head_padding = FIREFOX_HEAD_HEIGHT if self.sh.desired_capabilities [\"browserName\"] == \"firefox\" else 0\n self.scale_factor = self.sh.desired_capabilities.get(\"scale_factor\", 1)\n self.max_height = MAX_IMAGE_HEIGHT / self.scale_factor\n self.resize_delay = resize_delay\n\n def capture_page(self, viewport_only=False, padding=None):\n \"\"\"\n Entry point for a screenshot of the whole page. This will send the screenshot off to the correct methods\n depending on whether you need paginated screenshots, just the current viewport area, or the whole page in\n one large shot.\n :param\n - viewport_only: bool - Whether to capture just the viewport's visible area or not\n :return\n - StringIO: A StingIO object containing the captured image(s)\n \"\"\"\n try:\n if self.headless:\n return self._capture_headless_page(viewport_only)\n elif viewport_only:\n return self._capture_single_viewport()\n elif self.paginated:\n return self._capture_paginated_page(padding)\n else:\n return self._capture_full_page()\n\n except SeleniumHelperExceptions as selenium_error:\n message = \"A selenium issue arose while taking the screenshot\".format()\n error = SeleniumError(message, selenium_error)\n raise error\n except Exception as e:\n message = \"Unhandled exception while taking the screenshot | {0}\".format(e)\n raise ScreenshotException(message, stacktrace=traceback.format_exc())\n\n def capture_scrolling_element(self, css_selector, viewport_only=True, scroll_padding=None):\n \"\"\"\n This method will scroll an element one height (with padding) and take a screenshot each scroll until the element\n has been scrolled to the bottom. You can choose to capture the whole page (helpful when the scrollable element\n is taller than the viewport) or just the viewport area\n :param\n - css_selector: string - The css selector for the element that you plan to scroll\n - viewport_only: bool - Whether to capture just the viewport's visible area or not (each screenshot\n after scrolling)\n - scroll_padding: int - Overwrites the default scroll padding for the class. This can be used when the\n element, or site, have greatly different scroll padding numbers\n :return\n - StringIO: list - A list containing multiple StringIO image objects\n \"\"\"\n padding = scroll_padding if scroll_padding else self.scroll_padding\n\n try:\n image_list = []\n # Scroll the element to the top\n self.sh.scroll_an_element(css_selector, scroll_top=True)\n\n while True:\n if self.headless:\n image_list.append(self._capture_headless_page(viewport_only))\n elif viewport_only:\n image_list.append(self._capture_single_viewport())\n else:\n image_list.append(self._capture_full_page())\n\n if self.sh.get_is_element_scroll_position_at_bottom(css_selector):\n # Stop capturing once you're at the bottom\n break\n else:\n # Scroll down for the next one!\n self.sh.scroll_an_element(css_selector, scroll_padding=padding)\n\n return image_list\n\n except SeleniumHelperExceptions as selenium_error:\n message = \"A selenium issue arose while trying to capture the scrolling element\"\n error = SeleniumError(message, selenium_error)\n raise error\n except Exception as e:\n message = \"Unhandled exception while taking the scrolling screenshot \" \\\n \"of the element '{0}' | {1}\".format(css_selector, e)\n raise ScreenshotException(message,\n stacktrace=traceback.format_exc(),\n details={\"css_selector\": css_selector})\n\n def capture_horizontal_scrolling_element(self, css_selector, viewport_only=True, scroll_padding=None):\n \"\"\"\n This method will scroll an element horizontally one width (with padding) and take a screenshot each scroll until\n the element has been scrolled to the right. You can choose to capture the whole page (helpful when the\n scrollable element is taller than the viewport) or just the viewport area.\n\n :param\n - css_selector: string - The css selector for the element that you plan to scroll\n - viewport_only: bool - Whether to capture just the viewport's visible area or not (each screenshot\n after scrolling)\n - scroll_padding: int - Overwrites the default scroll padding for the class. This can be used when the\n element, or site, have greatly different scroll padding numbers\n :return\n - StringIO: list - A list containing multiple StringIO image objects\n \"\"\"\n padding = scroll_padding if scroll_padding else self.scroll_padding\n\n try:\n image_list = []\n # Scroll the element to the top\n self.sh.scroll_an_element(css_selector, scroll_left=True)\n\n while True:\n # - Capture the image\n if viewport_only:\n image_list.append(self._capture_single_viewport())\n else:\n image_list.append(self._capture_full_page())\n\n if self.sh.get_is_element_scroll_position_at_most_right(css_selector):\n # - Stop capturing once you're at the most right\n break\n else:\n # - Scroll right for the next one!\n self.sh.scroll_an_element(css_selector, scroll_padding=padding, scroll_horizontal=True)\n\n return image_list\n\n except SeleniumHelperExceptions as selenium_error:\n message = \"A selenium issue arose while trying to capture the scrolling element\"\n error = SeleniumError(message, selenium_error)\n raise error\n except Exception as e:\n message = \"Unhandled exception while taking the scrolling screenshot \" \\\n \"of the element '{0}' | {1}\".format(css_selector, e)\n raise ScreenshotException(message,\n stacktrace=traceback.format_exc(),\n details={\"css_selector\": css_selector})\n\n def _capture_single_viewport(self):\n \"\"\"\n Grabs an image of the page and then craps it to just the visible / viewport area\n :return\n - StringIO: A StingIO object containing the captured image\n \"\"\"\n cropped_image = self._get_image_data(viewport_only=True)\n return self._create_image_file(cropped_image)\n\n def _capture_full_page(self):\n \"\"\"\n Captures an image of the whole page. If there are sitcky elements, as specified by the footers and headers\n class variables the code will, the code will capture them only where appropriate ie. headers on top, footers on\n bottom. Otherwise the whole screen is sent back as it is currently set up.\n :return\n - StringIO: A StingIO object containing the captured image\n \"\"\"\n if self.headers and self.footers:\n # Capture viewport size window of the headers\n self.sh.scroll_window_to_position(0)\n self._hide_elements(self.footers)\n header_image = self._get_image_data(True)\n\n # - Capture the page from the bottom without headers\n self._show_elements(self.footers)\n #TODO: Update when scroll position updates to have a scroll to bottom option\n self.sh.scroll_window_to_position(40000)\n self._hide_elements(self.headers)\n footer_image = self._get_image_data()\n\n # Show all header elements again\n self._show_elements(self.headers)\n\n # Send the two images off to get merged into one\n image_data = self._crop_and_stitch_image(header_image, footer_image)\n elif self.headers:\n # Scroll to the top so that the headers are not covering content\n self.sh.scroll_window_to_position(0)\n time.sleep(0.5)\n image_data = self._get_image_data()\n elif self.footers:\n # Scroll to the bottom so that the footer items are not covering content\n self.sh.scroll_window_to_position(40000)\n time.sleep(0.5)\n image_data = self._get_image_data()\n else:\n image_data = self._get_image_data()\n\n return self._create_image_file(image_data)\n\n def _hide_elements(self, css_selectors):\n \"\"\"\n Hides all elements in the given list\n :param\n - css_selectors: list - A list of the elements you would like to hide\n \"\"\"\n for selector in css_selectors:\n try:\n self.sh.hide_element(selector)\n # Continue to the next item is this one did not exist or was already not visible\n except ElementNotVisibleError:\n pass\n except ElementError:\n pass\n\n def _show_elements(self, css_selectors):\n \"\"\"\n Shows all elements in the given list\n :param\n - css_selectors: list - A list of the elements you would like to make visible\n \"\"\"\n # Show footer items again\n for selector in css_selectors:\n try:\n self.sh.show_element(selector)\n # Continue to the next item is this one did not exist\n except ElementError:\n pass\n\n def _capture_headless_page(self, viewport_only):\n if self.paginated and not viewport_only:\n return self._capture_headless_paginated_page()\n\n # Store the current size and scroll position of the browser\n width, height = self.sh.get_window_size()\n current_scroll_position = self.sh.get_window_current_scroll_position()\n\n if not viewport_only:\n content_height = self.sh.get_content_height(self.content_container_selector)\n if content_height > self.max_height:\n self.sh.resize_browser(width, self.max_height + self.head_padding)\n time.sleep(self.resize_delay)\n elif height < content_height:\n self.sh.resize_browser(width, content_height + self.head_padding)\n time.sleep(self.resize_delay)\n self.sh.scroll_window_to_position(scroll_bottom=True)\n time.sleep(self.resize_delay)\n\n if content_height > self.max_height:\n images_list = []\n number_of_loops = int(math.ceil(content_height / self.max_height))\n\n # Loop through, starting at one for multiplication purposes\n for i in range(1, number_of_loops + 1):\n image_data = self.sh.get_screenshot_base64()\n image = Image.open(StringIO(image_data.decode('base64')))\n images_list.append(image)\n self.sh.scroll_window_to_position(self.max_height * i)\n\n # Combine al of the images into one capture\n image = self._combine_vertical_images(images_list, content_height)\n else:\n # Gather image byte data\n image_data = self.sh.get_screenshot_base64()\n # Create an image canvas and write the byte data to it\n image = Image.open(StringIO(image_data.decode('base64')))\n\n else:\n # Gather image byte data\n image_data = self.sh.get_screenshot_base64()\n # Create an image canvas and write the byte data to it\n image = Image.open(StringIO(image_data.decode('base64')))\n\n # - Return the browser to its previous size and scroll position\n if not viewport_only:\n self.sh.resize_browser(width, height)\n self.sh.scroll_window_to_position(current_scroll_position)\n time.sleep(self.resize_delay)\n\n return self._create_image_file(image)\n\n def _combine_vertical_images(self, images_list, content_height):\n height_of_full_images = 0\n total_height = 0\n total_width = 0\n\n # Make the last image the height of the remaining content\n for image in images_list[:-1]:\n height_of_full_images += image.size[1]\n remaining_height = (content_height * self.scale_factor) - height_of_full_images\n\n images_list[-1] = images_list[-1].crop((0,\n images_list[-1].size[1] - remaining_height,\n images_list[-1].size[0],\n images_list[-1].size[1]))\n\n for image in images_list:\n total_width = image.size[0] if image.size[0] > total_width else total_width\n total_height += image.size[1]\n\n resulting_image = Image.new('RGB', (total_width, total_height))\n current_height = 0\n for i, image in enumerate(images_list):\n resulting_image.paste(im=image, box=(0, current_height))\n current_height += image.size[1]\n\n return resulting_image\n\n def _capture_paginated_page(self, padding=None):\n \"\"\"\n Captures the page viewport by viewport, leaving an overlap of pixels the height of the self.padding variable\n between each image\n \"\"\"\n image_list = []\n scroll_padding = padding if padding else self.scroll_padding\n\n # Scroll page to the top\n self.sh.scroll_window_to_position(0)\n\n current_scroll_position = 0\n viewport_height = self.sh.driver.execute_script(\"return document.documentElement.clientHeight\")\n\n while True:\n # Capture the image\n image_list.append(self._capture_single_viewport())\n\n # Scroll for the next one!\n self.sh.scroll_window_to_position(current_scroll_position + viewport_height - scroll_padding)\n time.sleep(0.25)\n new_scroll_position = self.sh.get_window_current_scroll_position()\n\n # Break if the scroll position did not change (because it was at the bottom)\n if new_scroll_position == current_scroll_position:\n break\n else:\n current_scroll_position = new_scroll_position\n\n return image_list\n\n def _capture_headless_paginated_page(self, padding=None):\n \"\"\"\n Captures the page viewport by viewport, leaving an overlap of pixels the height of the self.padding variable\n between each image\n \"\"\"\n image_list = []\n scroll_padding = padding if padding else self.scroll_padding\n\n # Scroll page to the top\n self.sh.scroll_window_to_position(0)\n\n current_scroll_position = 0\n viewport_height = self.sh.driver.execute_script(\"return document.documentElement.clientHeight\")\n\n while True:\n # Capture the image\n image_data = self.sh.get_screenshot_base64()\n image_file = self._create_image_file(Image.open(StringIO(image_data.decode('base64'))))\n image_list.append(image_file)\n\n # Scroll for the next one!\n self.sh.scroll_window_to_position(current_scroll_position + viewport_height - scroll_padding)\n time.sleep(0.25)\n new_scroll_position = self.sh.get_window_current_scroll_position()\n\n # Break if the scroll position did not change (because it was at the bottom)\n if new_scroll_position == current_scroll_position:\n break\n else:\n current_scroll_position = new_scroll_position\n\n return image_list\n\n def _get_image_data(self, viewport_only=False):\n \"\"\"\n Creates an Image() canvas of the page. The image is cropped to be only the viewport area if specified.\n :param\n - viewport_only: bool - Captures only the visible /viewport area if true\n\n :return\n - image: Image() - The image canvas of the captured data\n \"\"\"\n # - Capture the image\n # Gather image byte data\n image_data = self.sh.get_screenshot_base64()\n # Create an image canvas and write the byte data to it\n image = Image.open(StringIO(image_data.decode('base64')))\n\n # - Crop the image to just the visible area\n # Top of the viewport\n current_scroll_position = self.sh.get_window_current_scroll_position()\n\n # Viewport Dimensions\n viewport_width, viewport_height = self.sh.get_viewport_size()\n\n # Image size of data returned by Selenium\n image_height, image_width = image.size\n\n if viewport_only:\n # Calculate the visible area\n crop_box = (0, current_scroll_position, viewport_width, current_scroll_position + viewport_height)\n\n # Crop everything of the image but the visible area\n cropped_image = image.crop(crop_box)\n return cropped_image\n else:\n # Calculate the visible area\n crop_box = (0, 0, viewport_width, image_width)\n\n # Crop everything of the image but the visible area\n cropped_image = image.crop(crop_box)\n return cropped_image\n\n def _crop_and_stitch_image(self, header_image, footer_image):\n \"\"\"\n This object takes in a header and footer image. It then searched for a block of 100 mixles that matches between\n the two images. Once it finds this point the footer image is cropped above the \"match\" point. A new canvas is\n then created that is the total height of both images. The two images are then copied onto a new canvas to create\n the final image, headers on top, footers on the bottom.\n :param\n - header_image: Image() - The top of the page, usually displays all of the headers elements\n - footer_image: Image() - The bottom of the page, usually displays all of the footer elements\n :return\n - stitched_image: Image() - The resulting image of the crop and stitching of the header and footer images\n \"\"\"\n try:\n # Create Pixel Row arrays from each image\n header_array = numpy.asarray(header_image)\n footer_array = numpy.asarray(footer_image)\n\n # - Find a place in both images that match then crop and stitch them at that location\n crop_row = 0\n header_image_height = header_image.height\n # Set the offset to the height of the image if the height is less than the offset\n if self.pixel_match_offset > header_image_height:\n self.pixel_match_offset = header_image_height\n\n # - Find the pixel row in the footer image that matches the bottom row in the header image\n # Grab the last 100 rows of header_image\n header_last_hundred_rows = header_array[header_image_height - self.pixel_match_offset: header_image_height]\n\n # Iterates throughout the check, will match the height of the row being checked in the image.\n for i, footer_row in enumerate(footer_array):\n # Jump out if the crop row has been set\n if crop_row != 0:\n break\n\n # Check if the current row being inspected matches the header row 100 pixels above the bottom\n if numpy.array_equal(footer_row, header_last_hundred_rows[0]):\n # It is a match!\n for y, row in enumerate(header_last_hundred_rows):\n # Check that the 100 footer rows above the matching row also match the bottom 100 of\n # the header image we grabbed at the start of this check\n if numpy.array_equal(footer_array[i + y], header_last_hundred_rows[y]):\n # Check whether we've found 100 matching rows or not\n if y == self.pixel_match_offset - 1:\n # Yes! All 100 matched. Set the crop row to this row\n crop_row = i + self.pixel_match_offset\n break\n\n # If no rows matched, crop at height of header image\n if crop_row == 0:\n crop_row = header_image_height\n\n # - Crop the top of the footer image off above the line that matches the header image's bottom row\n # Create the crop box that outlines what to remove from the footer image\n footer_image_width = footer_image.size[0]\n footer_image_height = footer_image.size[1]\n crop_box = (0, crop_row, footer_image_width, footer_image_height)\n # Perform the crop\n cropped_footer_image = footer_image.crop(crop_box)\n\n # Grab the new height of the footer image\n cropped_footer_image_height = cropped_footer_image.size[1]\n\n # Create a blank image canvas that is as tall the footer and header images combined\n total_height = header_image_height + cropped_footer_image_height\n stitched_image = Image.new(\"RGB\", (footer_image_width, total_height))\n\n # - Paste the header and footer images onto the canvas\n # Paste the header image at the top\n stitched_image.paste(header_image, (0, 0))\n # Paste the footer image directly below the header image\n stitched_image.paste(cropped_footer_image, (0, header_image_height))\n\n return stitched_image\n\n except Exception as e:\n message = \"Error while cropping and stitching a full page screenshot | {0}\".format(e)\n raise ScreenshotException(message, stacktrace=traceback.format_exc())\n\n def _create_image_file(self, image):\n \"\"\"\n This method takes an Image() variable and saves it into a StringIO \"file\".\n :param\n - image_data: Image() - The image to be saved into the StringIO object\n\n :return\n - image_file: StingIO() - The stringIO object containing the saved image\n \"\"\"\n # Instantiate the file object\n image_file = StringIO()\n # Save the image canvas to the file as the given file type\n image.save(image_file, self.file_extenson.upper())\n # Set the file marker back to the beginning\n image_file.seek(0)\n\n return image_file\n\n\nclass ScreenshotException(Exception):\n def __init__(self, msg, stacktrace=None, details=None):\n self.msg = msg\n self.details = {} if details is None else details\n self.details[\"stracktrace\"] = stacktrace\n super(ScreenshotException, self).__init__()\n\n def __str__(self):\n exception_msg = \"Screenshot Exception: \\n\"\n detail_string = \"Exception Details:\\n\"\n for key, value in self.details.items():\n detail_string += \"{0}: {1}\\n\".format(key, value)\n exception_msg += detail_string\n exception_msg += \"Message: {0}\".format(self.msg)\n\n return exception_msg\n\n\nclass SeleniumError(ScreenshotException):\n def __init__(self, message, selenium_helper_exception):\n new_message = \"{0} | {1}\".format(message, selenium_helper_exception.msg)\n super(SeleniumError, self).__init__(msg=new_message,\n stacktrace=selenium_helper_exception.stacktrace,\n details=selenium_helper_exception.details)\n" ]
[ [ "numpy.asarray", "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
feng-y16/Hamiltonian-Generative-Networks
[ "702d3ff3aec40eba20e17c5a1612b5b0b1e2f831", "702d3ff3aec40eba20e17c5a1612b5b0b1e2f831" ]
[ "train.py", "environments/gravity.py" ]
[ "\"\"\"Script to train the Hamiltonian Generative Network\n\"\"\"\nimport ast\nimport argparse\nimport copy\nimport pprint\nimport os\nimport warnings\nimport yaml\n\nimport numpy as np\nimport torch\nimport tqdm\n\nfrom utilities.integrator import Integrator\nfrom utilities.training_logger import TrainingLogger\nfrom utilities import loader\nfrom utilities.loader import load_hgn, get_online_dataloaders, get_offline_dataloaders\nfrom utilities.losses import reconstruction_loss, kld_loss, geco_constraint\nfrom utilities.statistics import mean_confidence_interval\n\ndef _avoid_overwriting(experiment_id):\n # This function throws an error if the given experiment data already exists in runs/\n logdir = os.path.join('runs', experiment_id)\n if os.path.exists(logdir):\n assert len(os.listdir(logdir)) == 0,\\\n f'Experiment id {experiment_id} already exists in runs/. Remove it, change the name ' \\\n f'in the yaml file.'\n\n\nclass HgnTrainer:\n\n def __init__(self, params, resume=False):\n \"\"\"Instantiate and train the Hamiltonian Generative Network.\n\n Args:\n params (dict): Experiment parameters (see experiment_params folder).\n \"\"\"\n\n self.params = params\n self.resume = resume\n\n if not resume: # Fail if experiment_id already exist in runs/\n _avoid_overwriting(params[\"experiment_id\"])\n\n # Set device\n self.device = params[\"device\"]\n if \"cuda\" in self.device and not torch.cuda.is_available():\n warnings.warn(\n \"Warning! Set to train in GPU but cuda is not available. Device is set to CPU.\")\n self.device = \"cpu\"\n\n # Get dtype, will raise a 'module 'torch' has no attribute' if there is a typo\n self.dtype = torch.__getattribute__(params[\"networks\"][\"dtype\"])\n\n # Load hgn from parameters to deice\n self.hgn = load_hgn(params=self.params,\n device=self.device,\n dtype=self.dtype)\n if 'load_path' in self.params:\n self.load_and_reset(self.params, self.device, self.dtype)\n\n # Either generate data on-the-fly or load the data from disk\n if \"train_data\" in self.params[\"dataset\"]:\n print(\"Training with OFFLINE data...\")\n self.train_data_loader, self.test_data_loader = get_offline_dataloaders(self.params)\n else:\n print(\"Training with ONLINE data...\")\n self.train_data_loader, self.test_data_loader = get_online_dataloaders(self.params)\n\n # Initialize training logger\n self.training_logger = TrainingLogger(\n hyper_params=self.params,\n loss_freq=100,\n rollout_freq=1000,\n model_freq=10000\n )\n\n # Initialize tensorboard writer\n self.model_save_file = os.path.join(\n self.params[\"model_save_dir\"],\n self.params[\"experiment_id\"]\n )\n\n # Define optimization modules\n optim_params = [\n {\n 'params': self.hgn.encoder.parameters(),\n 'lr': params[\"optimization\"][\"encoder_lr\"]\n },\n {\n 'params': self.hgn.transformer.parameters(),\n 'lr': params[\"optimization\"][\"transformer_lr\"]\n },\n {\n 'params': self.hgn.hnn.parameters(),\n 'lr': params[\"optimization\"][\"hnn_lr\"]\n },\n {\n 'params': self.hgn.decoder.parameters(),\n 'lr': params[\"optimization\"][\"decoder_lr\"]\n },\n ]\n self.optimizer = torch.optim.Adam(optim_params)\n\n def load_and_reset(self, params, device, dtype):\n \"\"\"Load the HGN from the path specified in params['load_path'] and reset the networks in\n params['reset'].\n\n Args:\n params (dict): Dictionary with all the necessary parameters to load the networks.\n device (str): 'gpu:N' or 'cpu'\n dtype (torch.dtype): Data type to be used in computations.\n \"\"\"\n self.hgn.load(params['load_path'])\n if 'reset' in params:\n if isinstance(params['reset'], list):\n for net in params['reset']:\n assert net in ['encoder', 'decoder', 'hamiltonian', 'transformer']\n else:\n assert params['reset'] in ['encoder', 'decoder', 'hamiltonian', 'transformer']\n if 'encoder' in params['reset']:\n self.hgn.encoder = loader.instantiate_encoder(params, device, dtype)\n if 'decoder' in params['reset']:\n self.hgn.decoder = loader.instantiate_decoder(params, device, dtype)\n if 'transformer' in params['reset']:\n self.hgn.transformer = loader.instantiate_transformer(params, device, dtype)\n if 'hamiltonian' in params['reset']:\n self.hgn.hnn = loader.instantiate_hamiltonian(params, device, dtype)\n\n def training_step(self, rollouts):\n \"\"\"Perform a training step with the given rollouts batch.\n\n Args:\n rollouts (torch.Tensor): Tensor of shape (batch_size, seq_len, channels, height, width)\n corresponding to a batch of sampled rollouts.\n\n Returns:\n A dictionary of losses and the model's prediction of the rollout. The reconstruction loss and\n KL divergence are floats and prediction is the HGNResult object with data of the forward pass.\n \"\"\"\n self.optimizer.zero_grad()\n\n rollout_len = rollouts.shape[1]\n input_frames = self.params['optimization']['input_frames']\n assert(input_frames <= rollout_len) # optimization.use_steps must be smaller (or equal) to rollout.sequence_length\n roll = rollouts[:, :input_frames]\n\n hgn_output = self.hgn.forward(rollout_batch=roll, n_steps=rollout_len - input_frames)\n target = rollouts[:, input_frames-1:] # Fit first input_frames and try to predict the last + the next (rollout_len - input_frames)\n prediction = hgn_output.reconstructed_rollout\n\n if self.params[\"networks\"][\"variational\"]:\n tol = self.params[\"geco\"][\"tol\"]\n alpha = self.params[\"geco\"][\"alpha\"]\n lagrange_mult_param = self.params[\"geco\"][\"lagrange_multiplier_param\"]\n\n C, rec_loss = geco_constraint(target, prediction, tol) # C has gradient\n\n # Compute moving average of constraint C (without gradient)\n if self.C_ma is None:\n self.C_ma = C.detach()\n else:\n self.C_ma = alpha * self.C_ma + (1 - alpha) * C.detach()\n C_curr = C.detach().item() # keep track for logging\n C = C + (self.C_ma - C.detach()) # Move C without affecting its gradient\n\n # Compute KL divergence\n mu = hgn_output.z_mean\n logvar = hgn_output.z_logvar\n kld = kld_loss(mu=mu, logvar=logvar)\n\n # normalize by number of frames, channels and pixels per frame\n kld_normalizer = prediction.flatten(1).size(1)\n kld = kld / kld_normalizer\n\n # Compute losses\n train_loss = kld + self.langrange_multiplier * C\n\n # clamping the langrange multiplier to avoid inf values\n self.langrange_multiplier = self.langrange_multiplier * torch.exp(\n lagrange_mult_param * C.detach())\n self.langrange_multiplier = torch.clamp(self.langrange_multiplier, 1e-10, 1e10)\n\n losses = {\n 'loss/train': train_loss.item(),\n 'loss/kld': kld.item(),\n 'loss/C': C_curr,\n 'loss/C_ma': self.C_ma.item(),\n 'loss/rec': rec_loss.item(),\n 'other/langrange_mult': self.langrange_multiplier.item()\n }\n\n else: # not variational\n # Compute frame reconstruction error\n train_loss = reconstruction_loss(\n target=target,\n prediction=prediction)\n losses = {'loss/train': train_loss.item()}\n\n train_loss.backward()\n self.optimizer.step()\n\n return losses, hgn_output\n\n def fit(self):\n \"\"\"The trainer fits an HGN.\n\n Returns:\n (HGN) An HGN model that has been fitted to the data\n \"\"\"\n\n # Initial values for geco algorithm\n if self.params[\"networks\"][\"variational\"]:\n self.langrange_multiplier = self.params[\"geco\"][\"initial_lagrange_multiplier\"]\n self.C_ma = None\n\n # TRAIN\n for ep in range(self.params[\"optimization\"][\"epochs\"]):\n print(\"Epoch %s / %s\" % (str(ep + 1), str(self.params[\"optimization\"][\"epochs\"])))\n pbar = tqdm.tqdm(self.train_data_loader)\n for batch_idx, rollout_batch in enumerate(pbar):\n # Move to device and change dtype\n rollout_batch = rollout_batch.to(self.device).type(self.dtype)\n\n # Do an optimization step\n losses, prediction = self.training_step(rollouts=rollout_batch)\n\n # Log progress\n self.training_logger.step(losses=losses,\n rollout_batch=rollout_batch,\n prediction=prediction,\n model=self.hgn)\n\n # Progress-bar msg\n msg = \", \".join([\n f\"{k}: {v:.2e}\" for k, v in losses.items() if v is not None\n ])\n pbar.set_description(msg)\n # Save model\n self.hgn.save(self.model_save_file)\n\n self.test()\n return self.hgn\n \n def compute_reconst_kld_errors(self, dataloader):\n \"\"\"Computes reconstruction error and KL divergence.\n\n Args:\n dataloader (torch.utils.data.DataLoader): DataLoader to retrieve errors from.\n\n Returns:\n (reconst_error_mean, reconst_error_h), (kld_mean, kld_h): Tuples where the mean and 95%\n conficence interval is shown.\n \"\"\"\n first = True\n pbar = tqdm.tqdm(dataloader)\n \n for _, rollout_batch in enumerate(pbar):\n # Move to device and change dtype\n rollout_batch = rollout_batch.to(self.device).type(self.dtype)\n rollout_len = rollout_batch.shape[1]\n input_frames = self.params['optimization']['input_frames']\n assert(input_frames <= rollout_len) # optimization.use_steps must be smaller (or equal) to rollout.sequence_length\n roll = rollout_batch[:, :input_frames]\n hgn_output = self.hgn.forward(rollout_batch=roll, n_steps=rollout_len - input_frames)\n target = rollout_batch[:, input_frames-1:] # Fit first input_frames and try to predict the last + the next (rollout_len - input_frames)\n prediction = hgn_output.reconstructed_rollout\n error = reconstruction_loss(\n target=target,\n prediction=prediction, mean_reduction=False).detach().cpu(\n ).numpy()\n if self.params[\"networks\"][\"variational\"]:\n kld = kld_loss(mu=hgn_output.z_mean, logvar=hgn_output.z_logvar, mean_reduction=False).detach().cpu(\n ).numpy()\n # normalize by number of frames, channels and pixels per frame\n kld_normalizer = prediction.flatten(1).size(1)\n kld = kld / kld_normalizer\n if first:\n first = False\n set_errors = error\n if self.params[\"networks\"][\"variational\"]:\n set_klds = kld\n else:\n set_errors = np.concatenate((set_errors, error))\n if self.params[\"networks\"][\"variational\"]:\n set_klds = np.concatenate((set_klds, kld))\n err_mean, err_h = mean_confidence_interval(set_errors)\n if self.params[\"networks\"][\"variational\"]:\n kld_mean, kld_h = mean_confidence_interval(set_klds)\n return (err_mean, err_h), (kld_mean, kld_h)\n else:\n return (err_mean, err_h), None\n \n def test(self):\n \"\"\"Test after the training is finished and logs result to tensorboard.\n \"\"\"\n print(\"Calculating final training error...\")\n (err_mean, err_h), kld = self.compute_reconst_kld_errors(self.train_data_loader)\n self.training_logger.log_error(\"Train reconstruction error\", err_mean, err_h)\n if kld is not None:\n kld_mean, kld_h = kld\n self.training_logger.log_error(\"Train KL divergence\", kld_mean, kld_h)\n\n print(\"Calculating final test error...\")\n (err_mean, err_h), kld = self.compute_reconst_kld_errors(self.test_data_loader)\n self.training_logger.log_error(\"Test reconstruction error\", err_mean, err_h)\n if kld is not None:\n kld_mean, kld_h = kld\n self.training_logger.log_error(\"Test KL divergence\", kld_mean, kld_h)\n\ndef _overwrite_config_with_cmd_arguments(config, args):\n if args.name is not None:\n config['experiment_id'] = args.name[0]\n if args.epochs is not None:\n config['optimization']['epochs'] = args.epochs[0]\n if args.dataset_path is not None:\n # Read the parameters.yaml file in the given dataset path\n dataset_config = _read_config(os.path.join(_args.dataset_path[0], 'parameters.yaml'))\n for key, value in dataset_config.items():\n config[key] = value\n if args.env is not None:\n if 'train_data' in config['dataset']:\n raise ValueError(\n f'--env was given but configuration is set for offline training: '\n f'train_data={config[\"dataset\"][\"train_data\"]}'\n )\n env_params = _read_config(DEFAULT_ENVIRONMENTS_PATH + args.env[0] + '.yaml')\n config['environment'] = env_params['environment']\n if args.params is not None:\n for p in args.params:\n key, value = p.split('=')\n ptr = config\n keys = key.split('.')\n for i, k in enumerate(keys):\n if i == len(keys) - 1:\n ptr[k] = ast.literal_eval(value)\n else:\n ptr = ptr[k]\n if args.load is not None:\n config['load_path'] = args.load[0]\n if args.reset is not None:\n config['reset'] = args.reset\n\n\ndef _read_config(config_file):\n with open(config_file, 'r') as f:\n config = yaml.load(f, Loader=yaml.FullLoader)\n return config\n\n\ndef _merge_configs(train_config, dataset_config):\n config = copy.deepcopy(train_config)\n for key, value in dataset_config.items():\n config[key] = value\n # If the config specifies a dataset path, we take the rollout from the configuration file\n # in the given dataset\n if 'dataset' in config and 'train_data' in config['dataset']:\n dataset_config = _read_config( # Read parameters.yaml in root of given dataset\n os.path.join(os.path.dirname(config['dataset']['train_data']), 'parameters.yaml'))\n config['dataset']['rollout'] = dataset_config['dataset']['rollout']\n return config\n\n\ndef _ask_confirmation(config):\n printer = pprint.PrettyPrinter(indent=4)\n print(f'The training will be run with the following configuration:')\n printed_config = copy.deepcopy(_config)\n printed_config.pop('networks')\n printer.pprint(printed_config)\n print('Proceed? (y/n):')\n if input() != 'y':\n print('Abort.')\n exit()\n\n\nif __name__ == \"__main__\":\n\n DEFAULT_TRAIN_CONFIG_FILE = \"experiment_params/train_config_default.yaml\"\n DEFAULT_DATASET_CONFIG_FILE = \"experiment_params/dataset_online_default.yaml\"\n DEFAULT_ENVIRONMENTS_PATH = \"experiment_params/default_environments/\"\n DEFAULT_SAVE_MODELS_DIR = \"saved_models/\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--train-config', action='store', nargs=1, type=str, required=True,\n help=f'Path to the training configuration yaml file.'\n )\n parser.add_argument(\n '--dataset-config', action='store', nargs=1, type=str, required=False,\n help=f'Path to the dataset configuration yaml file.'\n )\n parser.add_argument(\n '--name', action='store', nargs=1, required=False,\n help='If specified, this name will be used instead of experiment_id of the yaml file.'\n )\n parser.add_argument(\n '--epochs', action='store', nargs=1, type=int, required=False,\n help='The number of training epochs. If not specified, optimization.epochs of the '\n 'training configuration will be used.'\n )\n parser.add_argument(\n '--env', action='store', nargs=1, type=str, required=False,\n help='The environment to use (for online training only). Possible values are '\n '\\'pendulum\\', \\'spring\\', \\'two_bodies\\', \\'three_bodies\\', corresponding to '\n 'environment configurations in experiment_params/default_environments/. If not '\n 'specified, the environment specified in the given --dataset-config will be used.'\n )\n parser.add_argument(\n '--dataset-path', action='store', nargs=1, type=str, required=False,\n help='Path to a stored dataset to use for training. For offline training only. In this '\n 'case no dataset configuration file will be loaded.'\n )\n parser.add_argument(\n '--params', action='store', nargs='+', required=False,\n help='Override one or more parameters in the config. The format of an argument is '\n 'param_name=param_value. Nested parameters are accessible by using a dot, '\n 'i.e. --param dataset.img_size=32. IMPORTANT: lists must be enclosed in double '\n 'quotes, i.e. --param environment.mass:\"[0.5, 0.5]\".'\n )\n parser.add_argument(\n '-y', '-y', action='store_true', default=False, required=False,\n help='Whether to skip asking for user confirmation before starting the training.'\n )\n parser.add_argument(\n '--resume', action='store', required=False, nargs='?', default=None,\n help='NOT IMPLEMENTED YET. Resume the training from a saved model. If a path is provided, '\n 'the training will be resumed from the given checkpoint. Otherwise, the last '\n 'checkpoint will be taken from saved_models/<experiment_id>.'\n )\n parser.add_argument(\n '--load', action='store', type=str, required=False, nargs=1,\n help='Path from which to load the HGN.'\n )\n parser.add_argument(\n '--reset', action='store', nargs='+', required=False,\n help='Use only in combimation with --load, tells the trainer to reinstantiate the given '\n 'networks. Values: \\'encoder\\', \\'transformer\\', \\'decoder\\', \\'hamiltonian\\'.'\n )\n _args = parser.parse_args()\n\n # Read configurations\n _train_config = _read_config(_args.train_config[0])\n if _args.dataset_path is None: # Will use the dataset config file (or default if not given)\n _dataset_config_file = DEFAULT_DATASET_CONFIG_FILE if _args.dataset_config is None else \\\n _args.dataset_config[0]\n _dataset_config = _read_config(_dataset_config_file)\n _config = _merge_configs(_train_config, _dataset_config)\n else: # Will use the dataset given in the command line arguments\n assert _args.dataset_config is None, 'Both --dataset-path and --dataset-config were given.'\n _config = _train_config\n\n # Overwrite configuration with command line arguments\n _overwrite_config_with_cmd_arguments(_config, _args)\n\n # Show configuration and ask user for confirmation\n if not _args.y:\n _ask_confirmation(_config)\n\n # Train HGN network\n trainer = HgnTrainer(_config)\n hgn = trainer.fit()\n", "import warnings\n\nimport cv2\nimport numpy as np\n\nfrom environment import Environment, visualize_rollout\n\n\nclass NObjectGravity(Environment):\n\n \"\"\"N Object Gravity Atraction System\n\n Equations of movement are:\n\n m_i*q'' = G * sum_{i!=j} ( m_i*m_j*(q_j - q_i)/ abs(q_j - q_i)^3 )\n\n \"\"\"\n\n WORLD_SIZE = 3.\n\n def __init__(self, mass, g, orbit_noise=.01, q=None, p=None):\n \"\"\"Contructor for spring system\n\n Args:\n mass (list): List of floats corresponding to object masses (kg).\n g (float): Constant for the intensity of gravitational field (m^3/kg*s^2)\n orbit_noise (float, optional): Noise for object orbits when sampling initial conditions\n q (ndarray, optional): Object generalized positions in 2-D space: Positions (m). Defaults to None\n p (ndarray, optional): Object generalized momentums in 2-D space : Linear momentums (kg*m/s). Defaults to None\n Raises:\n NotImplementedError: If more than 7 objects are considered\n \"\"\"\n self.mass = mass\n self.colors = ['r', 'y', 'g', 'b', 'c', 'p', 'w']\n self.n_objects = len(mass)\n self.g = g\n self.orbit_noise = orbit_noise\n if self.n_objects > 3:\n raise NotImplementedError(\n 'Gravity interaction for ' + str(self.n_objects) + ' bodies is not implemented.')\n super().__init__(q=q, p=p)\n\n def set(self, q, p):\n \"\"\"Sets initial conditions for pendulum\n\n Args:\n q (ndarray): Object generalized positions in 2-D space: Positions (m)\n p (ndarray): Object generalized momentums in 2-D space : Linear momentums (kg*m/s)\n\n Raises:\n ValueError: If q and p are not in 2-D space or do not refer to all the objects in space\n \"\"\"\n if q is None or p is None:\n return\n if q.shape[0] != self.n_objects or p.shape[0] != self.n_objects:\n raise ValueError(\n \"q and p do not refer to the same number of objects in the system.\")\n if q.shape[-1] != 2 or p.shape[-1] != 2:\n raise ValueError(\n \"q and p must be in 2-D space: Position and Linear momentum.\")\n self.q = q.copy()\n self.p = p.copy()\n\n def get_world_size(self):\n \"\"\"Return world size for correctly render the environment.\n \"\"\"\n return self.WORLD_SIZE\n\n def get_max_noise_std(self):\n \"\"\"Return maximum noise std that keeps the environment stable.\"\"\"\n if self.n_objects == 2:\n return 0.05\n elif self.n_objects == 3:\n return 0.2\n else:\n return 0.\n\n def get_default_radius_bounds(self):\n \"\"\"Returns:\n radius_bounds (tuple): (min, max) radius bounds for the environment.\n \"\"\"\n if self.n_objects == 2:\n return (0.5, 1.5)\n elif self.n_objects == 3:\n return (0.9, 1.2)\n else:\n warnings.warn(\n 'Gravity for n > 3 objects can have undefined behavior.')\n return (0.3, 0.5)\n\n def _dynamics(self, t, states):\n \"\"\"Defines system dynamics\n\n Args:\n t (float): Time parameter of the dynamic equations.\n states (numpy.ndarray): 1-D array that contains the information of the phase\n state, in the format of np.array([q,p]).reshape(-1).\n\n Returns:\n equations (numpy.ndarray): Numpy array with derivatives of q and p w.r.t. time\n \"\"\"\n # Convert states to n_object arrays of q and p\n states_resh = states.reshape(2, self.n_objects, 2)\n dyn = np.zeros_like(states_resh)\n states_q = states_resh[0, :, :]\n states_p = states_resh[1, :, :]\n dyn[0, :, :] = states_p/(np.array(self.mass)[:, np.newaxis])\n\n # Distance calculation\n object_distance = np.zeros((self.n_objects, self.n_objects))\n for i in range(self.n_objects):\n for j in range(i, self.n_objects):\n object_distance[i, j] = np.linalg.norm(\n states_q[i] - states_q[j])\n object_distance[j, i] = object_distance[i, j]\n object_distance = np.power(object_distance, 3)/self.g\n\n for d in range(2):\n for i in range(self.n_objects):\n mom_term = 0\n for j in range(self.n_objects):\n if i != j:\n mom_term += self.mass[j]*(states_q[j, d] -\n states_q[i, d])/object_distance[i, j]\n dyn[1, i, d] += mom_term*self.mass[i]\n return dyn.reshape(-1)\n\n def _draw(self, res=32, color=True):\n \"\"\"Returns array of the environment evolution\n\n Args:\n res (int): Image resolution (images are square).\n color (bool): True if RGB, false if grayscale.\n\n Returns:\n vid (np.ndarray): Numpy array of shape (seq_len, height, width, channels)\n containing the rendered rollout as a sequence of images.\n \"\"\"\n q = self._rollout.reshape(2, self.n_objects, 2, -1)[0]\n length = q.shape[-1]\n vid = np.zeros((length, res, res, 3), dtype='float')\n ball_colors = self._default_ball_colors\n space_res = 2.*self.get_world_size()/res\n if self.n_objects == 2:\n factor = 0.55\n else:\n factor = 0.25\n for t in range(length):\n for n in range(self.n_objects):\n brush = self.colors[n]\n if brush == 'y':\n vid[t] = cv2.circle(vid[t],\n self._world_to_pixels(\n q[n, 0, t], q[n, 1, t], res),\n int(self.mass[n]*factor/space_res), ball_colors[0], -1)\n elif brush == 'r':\n vid[t] = cv2.circle(vid[t],\n self._world_to_pixels(\n q[n, 0, t], q[n, 1, t], res),\n int(self.mass[n]*factor/space_res), ball_colors[1], -1)\n elif brush == 'g':\n vid[t] = cv2.circle(vid[t],\n self._world_to_pixels(\n q[n, 0, t], q[n, 1, t], res),\n int(self.mass[n]*factor/space_res), ball_colors[2], -1)\n vid[t] = cv2.blur(cv2.blur(vid[t], (2, 2)), (2, 2))\n vid += self._default_background_color\n vid[vid > 1.] = 1.\n if not color:\n vid = np.expand_dims(np.max(vid, axis=-1), -1)\n return vid\n\n def _sample_init_conditions(self, radius_bound):\n \"\"\"Samples random initial conditions for the environment\n Args:\n radius_bound (float, float): Radius lower and upper bound of the phase state sampling.\n Optionally, it can be a string 'auto'. In that case, the value returned by\n get_default_radius_bounds() will be returned.\n \"\"\"\n radius_lb, radius_ub = radius_bound\n radius = np.random.rand()*(radius_ub - radius_lb) + radius_lb\n states = np.zeros((2, self.n_objects, 2))\n # first position\n pos = np.random.rand(2)*2. - 1\n pos = (pos/np.sqrt((pos**2).sum()))*radius\n\n # velocity that yields a circular orbit\n vel = self.__rotate2d(pos, theta=np.pi/2)\n if np.random.randn() < .5:\n vel = -vel\n if self.n_objects == 2:\n factor = 2\n vel /= (factor*radius**1.5)\n\n else:\n factor = np.sqrt(np.sin(np.pi/3)/(2*np.cos(np.pi/6)**2))\n vel *= factor/(radius**1.5)\n\n states[0, 0, :] = pos\n states[1, 0, :] = vel\n\n rot_angle = 2*np.pi/self.n_objects\n for i in range(1, self.n_objects):\n states[0, i, :] = self.__rotate2d(\n states[0, i - 1, :], theta=rot_angle)\n states[1, i, :] = self.__rotate2d(\n states[1, i - 1, :], theta=rot_angle)\n for i in range(self.n_objects):\n states[1, i, :] *= 1 + \\\n self.orbit_noise*(2*np.random.rand(2) - 1)\n self.set(states[0], states[1])\n\n def __rotate2d(self, p, theta):\n c, s = np.cos(theta), np.sin(theta)\n Rot = np.array([[c, -s], [s, c]])\n return np.dot(Rot, p.reshape(2, 1)).squeeze()\n\n\n# Sample code for sampling rollouts\nif __name__ == \"__main__\":\n\n og = NObjectGravity(mass=[1., 1.],\n g=1., orbit_noise=0.05)\n rolls = og.sample_random_rollouts(number_of_frames=30,\n delta_time=0.125,\n number_of_rollouts=1,\n img_size=32,\n noise_level=0.,\n radius_bound=(.5, 1.5),\n seed=None)\n idx = np.random.randint(rolls.shape[0])\n visualize_rollout(rolls[idx])\n" ]
[ [ "torch.optim.Adam", "torch.__getattribute__", "numpy.concatenate", "torch.cuda.is_available", "torch.clamp" ], [ "numpy.power", "numpy.cos", "numpy.linalg.norm", "numpy.sin", "numpy.max", "numpy.zeros_like", "numpy.random.randn", "numpy.random.rand", "numpy.array", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
puririshi98/benchmark
[ "2440b3b6e177a9b38011eff3ec25f3b6052acfd0", "79f554f1e1cf36f62994c78e0e6e5b360f554022", "79f554f1e1cf36f62994c78e0e6e5b360f554022", "df51ed9c1d6dbde1deef63f2a037a369f8554406", "79f554f1e1cf36f62994c78e0e6e5b360f554022", "79f554f1e1cf36f62994c78e0e6e5b360f554022", "2440b3b6e177a9b38011eff3ec25f3b6052acfd0", "df51ed9c1d6dbde1deef63f2a037a369f8554406", "9d75577382089b742a972800c7c892f831910d91", "79f554f1e1cf36f62994c78e0e6e5b360f554022" ]
[ "DeepLearningExamples/PyTorch/Recommendation/DLRM/preproc/parquet_to_binary.py", "DeepLearningExamples/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/object_detection/argmax_matcher.py", "DeepLearningExamples/TensorFlow2/LanguageModeling/BERT/official/nlp/modeling/networks/encoder_scaffold.py", "DeepLearningExamples/TensorFlow/Segmentation/UNet_Industrial/model/layers/pooling.py", "DeepLearningExamples/PyTorch/Classification/ConvNets/quant_main.py", "DeepLearningExamples/TensorFlow/Classification/ConvNets/utils/dali_utils.py", "DeepLearningExamples/PyTorch/Recommendation/DLRM/dlrm/nn/interactions.py", "DeepLearningExamples/TensorFlow/Segmentation/UNet_Industrial/model/layers/array_ops.py", "torchbenchmark/models/mobilenet_v2/__init__.py", "DeepLearningExamples/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/model/mask_rcnn.py" ]
[ "# Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport numpy as np\nimport pandas as pd\nimport os\nfrom joblib import Parallel, delayed\nimport glob\nimport argparse\nimport tqdm\nimport subprocess\n\ndef process_file(f, dst):\n label = '_c0'\n dense_columns = [f'_c{i}' for i in range(1, 14)]\n categorical_columns = [f'_c{i}' for i in range(14, 40)]\n all_columns_sorted = [f'_c{i}' for i in range(0, 40)]\n data = pd.read_parquet(f)\n data = data[all_columns_sorted]\n\n data[label] = data[label].astype(np.int32)\n data[dense_columns] = data[dense_columns].astype(np.float32)\n data[categorical_columns] = data[categorical_columns].astype(np.int32)\n\n data = data.to_records(index=False)\n data = data.tobytes()\n\n dst_file = dst + '/' + f.split('/')[-1] + '.bin'\n with open(dst_file, 'wb') as dst_fd:\n dst_fd.write(data)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--src_dir', type=str)\n parser.add_argument('--intermediate_dir', type=str)\n parser.add_argument('--dst_dir', type=str)\n parser.add_argument('--parallel_jobs', default=40, type=int)\n args = parser.parse_args()\n\n print('Processing train files...')\n train_src_files = glob.glob(args.src_dir + '/train/*.parquet')\n train_intermediate_dir = os.path.join(args.intermediate_dir, 'train')\n os.makedirs(train_intermediate_dir, exist_ok=True)\n\n Parallel(n_jobs=args.parallel_jobs)(delayed(process_file)(f, train_intermediate_dir) for f in tqdm.tqdm(train_src_files))\n\n print('Train files conversion done')\n\n print('Processing test files...')\n test_src_files = glob.glob(args.src_dir + '/test/*.parquet')\n test_intermediate_dir = os.path.join(args.intermediate_dir, 'test')\n os.makedirs(test_intermediate_dir, exist_ok=True)\n\n Parallel(n_jobs=args.parallel_jobs)(delayed(process_file)(f, test_intermediate_dir) for f in tqdm.tqdm(test_src_files))\n print('Test files conversion done')\n\n print('Processing validation files...')\n valid_src_files = glob.glob(args.src_dir + '/validation/*.parquet')\n valid_intermediate_dir = os.path.join(args.intermediate_dir, 'validation')\n os.makedirs(valid_intermediate_dir, exist_ok=True)\n\n Parallel(n_jobs=args.parallel_jobs)(delayed(process_file)(f, valid_intermediate_dir) for f in tqdm.tqdm(valid_src_files))\n print('Validation files conversion done')\n\n os.makedirs(args.dst_dir, exist_ok=True)\n\n print('Concatenating train files')\n os.system(f'cat {train_intermediate_dir}/*.bin > {args.dst_dir}/train_data.bin')\n\n print('Concatenating test files')\n os.system(f'cat {test_intermediate_dir}/*.bin > {args.dst_dir}/test_data.bin')\n\n print('Concatenating validation files')\n os.system(f'cat {valid_intermediate_dir}/*.bin > {args.dst_dir}/validation_data.bin')\n print('Done')\n\n\nif __name__ == '__main__':\n main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Argmax matcher implementation.\n\nThis class takes a similarity matrix and matches columns to rows based on the\nmaximum value per column. One can specify matched_thresholds and\nto prevent columns from matching to rows (generally resulting in a negative\ntraining example) and unmatched_theshold to ignore the match (generally\nresulting in neither a positive or negative training example).\n\nThis matcher is used in Fast(er)-RCNN.\n\nNote: matchers are used in TargetAssigners. There is a create_target_assigner\nfactory function for popular implementations.\n\"\"\"\nimport tensorflow as tf\n\nfrom mrcnn_tf2.object_detection import matcher, shape_utils\n\n\nclass ArgMaxMatcher(matcher.Matcher):\n \"\"\"Matcher based on highest value.\n\n This class computes matches from a similarity matrix. Each column is matched\n to a single row.\n\n To support object detection target assignment this class enables setting both\n matched_threshold (upper threshold) and unmatched_threshold (lower thresholds)\n defining three categories of similarity which define whether examples are\n positive, negative, or ignored:\n (1) similarity >= matched_threshold: Highest similarity. Matched/Positive!\n (2) matched_threshold > similarity >= unmatched_threshold: Medium similarity.\n Depending on negatives_lower_than_unmatched, this is either\n Unmatched/Negative OR Ignore.\n (3) unmatched_threshold > similarity: Lowest similarity. Depending on flag\n negatives_lower_than_unmatched, either Unmatched/Negative OR Ignore.\n For ignored matches this class sets the values in the Match object to -2.\n \"\"\"\n\n def __init__(self,\n matched_threshold,\n unmatched_threshold=None,\n negatives_lower_than_unmatched=True,\n force_match_for_each_row=False):\n \"\"\"Construct ArgMaxMatcher.\n\n Args:\n matched_threshold: Threshold for positive matches. Positive if\n sim >= matched_threshold, where sim is the maximum value of the\n similarity matrix for a given column. Set to None for no threshold.\n unmatched_threshold: Threshold for negative matches. Negative if\n sim < unmatched_threshold. Defaults to matched_threshold\n when set to None.\n negatives_lower_than_unmatched: Boolean which defaults to True. If True\n then negative matches are the ones below the unmatched_threshold,\n whereas ignored matches are in between the matched and umatched\n threshold. If False, then negative matches are in between the matched\n and unmatched threshold, and everything lower than unmatched is ignored.\n force_match_for_each_row: If True, ensures that each row is matched to\n at least one column (which is not guaranteed otherwise if the\n matched_threshold is high). Defaults to False. See\n argmax_matcher_test.testMatcherForceMatch() for an example.\n\n Raises:\n ValueError: if unmatched_threshold is set but matched_threshold is not set\n or if unmatched_threshold > matched_threshold.\n \"\"\"\n if (matched_threshold is None) and (unmatched_threshold is not None):\n raise ValueError('Need to also define matched_threshold when'\n 'unmatched_threshold is defined')\n self._matched_threshold = matched_threshold\n if unmatched_threshold is None:\n self._unmatched_threshold = matched_threshold\n else:\n if unmatched_threshold > matched_threshold:\n raise ValueError('unmatched_threshold needs to be smaller or equal'\n 'to matched_threshold')\n self._unmatched_threshold = unmatched_threshold\n if not negatives_lower_than_unmatched:\n if self._unmatched_threshold == self._matched_threshold:\n raise ValueError('When negatives are in between matched and '\n 'unmatched thresholds, these cannot be of equal '\n 'value. matched: %s, unmatched: %s',\n self._matched_threshold, self._unmatched_threshold)\n self._force_match_for_each_row = force_match_for_each_row\n self._negatives_lower_than_unmatched = negatives_lower_than_unmatched\n\n def _match(self, similarity_matrix):\n \"\"\"Tries to match each column of the similarity matrix to a row.\n\n Args:\n similarity_matrix: tensor of shape [N, M] representing any similarity\n metric.\n\n Returns:\n Match object with corresponding matches for each of M columns.\n \"\"\"\n\n def _match_when_rows_are_empty():\n \"\"\"Performs matching when the rows of similarity matrix are empty.\n\n When the rows are empty, all detections are false positives. So we return\n a tensor of -1's to indicate that the columns do not match to any rows.\n\n Returns:\n matches: int32 tensor indicating the row each column matches to.\n \"\"\"\n similarity_matrix_shape = shape_utils.combined_static_and_dynamic_shape(\n similarity_matrix)\n return -1 * tf.ones([similarity_matrix_shape[1]], dtype=tf.int32)\n\n def _match_when_rows_are_non_empty():\n \"\"\"Performs matching when the rows of similarity matrix are non empty.\n\n Returns:\n matches: int32 tensor indicating the row each column matches to.\n \"\"\"\n # Matches for each column\n matches = tf.argmax(input=similarity_matrix, axis=0, output_type=tf.int32)\n\n # Deal with matched and unmatched threshold\n if self._matched_threshold is not None:\n # Get logical indices of ignored and unmatched columns as tf.int64\n matched_vals = tf.reduce_max(input_tensor=similarity_matrix, axis=0)\n below_unmatched_threshold = tf.greater(self._unmatched_threshold,\n matched_vals)\n between_thresholds = tf.logical_and(\n tf.greater_equal(matched_vals, self._unmatched_threshold),\n tf.greater(self._matched_threshold, matched_vals))\n\n if self._negatives_lower_than_unmatched:\n matches = self._set_values_using_indicator(matches,\n below_unmatched_threshold,\n -1)\n matches = self._set_values_using_indicator(matches,\n between_thresholds,\n -2)\n else:\n matches = self._set_values_using_indicator(matches,\n below_unmatched_threshold,\n -2)\n matches = self._set_values_using_indicator(matches,\n between_thresholds,\n -1)\n\n if self._force_match_for_each_row:\n similarity_matrix_shape = shape_utils.combined_static_and_dynamic_shape(\n similarity_matrix)\n force_match_column_ids = tf.argmax(input=similarity_matrix, axis=1,\n output_type=tf.int32)\n force_match_column_indicators = tf.one_hot(\n force_match_column_ids, depth=similarity_matrix_shape[1])\n force_match_row_ids = tf.argmax(input=force_match_column_indicators, axis=0,\n output_type=tf.int32)\n force_match_column_mask = tf.cast(\n tf.reduce_max(input_tensor=force_match_column_indicators, axis=0), tf.bool)\n final_matches = tf.where(force_match_column_mask,\n force_match_row_ids, matches)\n return final_matches\n else:\n return matches\n\n if similarity_matrix.shape.is_fully_defined():\n if similarity_matrix.shape[0].value == 0:\n return _match_when_rows_are_empty()\n else:\n return _match_when_rows_are_non_empty()\n else:\n return tf.cond(\n pred=tf.greater(tf.shape(input=similarity_matrix)[0], 0),\n true_fn=_match_when_rows_are_non_empty, false_fn=_match_when_rows_are_empty)\n\n def _set_values_using_indicator(self, x, indicator, val):\n \"\"\"Set the indicated fields of x to val.\n\n Args:\n x: tensor.\n indicator: boolean with same shape as x.\n val: scalar with value to set.\n\n Returns:\n modified tensor.\n \"\"\"\n indicator = tf.cast(indicator, x.dtype)\n return tf.add(tf.multiply(x, 1 - indicator), val * indicator)\n", "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Transformer-based text encoder network.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# from __future__ import google_type_annotations\nfrom __future__ import print_function\n\nimport inspect\nimport tensorflow as tf\n\nfrom official.nlp.modeling import layers\n\n\[email protected]_keras_serializable(package='Text')\nclass EncoderScaffold(tf.keras.Model):\n \"\"\"Bi-directional Transformer-based encoder network scaffold.\n\n This network allows users to flexibly implement an encoder similar to the one\n described in \"BERT: Pre-training of Deep Bidirectional Transformers for\n Language Understanding\" (https://arxiv.org/abs/1810.04805).\n\n In this network, users can choose to provide a custom embedding subnetwork\n (which will replace the standard embedding logic) and/or a custom hidden layer\n class (which will replace the Transformer instantiation in the encoder). For\n each of these custom injection points, users can pass either a class or a\n class instance. If a class is passed, that class will be instantiated using\n the 'embedding_cfg' or 'hidden_cfg' argument, respectively; if an instance\n is passed, that instance will be invoked. (In the case of hidden_cls, the\n instance will be invoked 'num_hidden_instances' times.\n\n If the hidden_cls is not overridden, a default transformer layer will be\n instantiated.\n\n Attributes:\n num_output_classes: The output size of the classification layer.\n classification_layer_initializer: The initializer for the classification\n layer.\n classification_layer_dtype: The dtype for the classification layer.\n embedding_cls: The class or instance to use to embed the input data. This\n class or instance defines the inputs to this encoder. If embedding_cls is\n not set, a default embedding network (from the original BERT paper) will\n be created.\n embedding_cfg: A dict of kwargs to pass to the embedding_cls, if it needs to\n be instantiated. If embedding_cls is not set, a config dict must be\n passed to 'embedding_cfg' with the following values:\n \"vocab_size\": The size of the token vocabulary.\n \"type_vocab_size\": The size of the type vocabulary.\n \"hidden_size\": The hidden size for this encoder.\n \"max_seq_length\": The maximum sequence length for this encoder.\n \"seq_length\": The sequence length for this encoder.\n \"initializer\": The initializer for the embedding portion of this encoder.\n \"dropout_rate\": The dropout rate to apply before the encoding layers.\n \"dtype\": (Optional): The dtype of the embedding layers.\n embedding_data: A reference to the embedding weights that will be used to\n train the masked language model, if necessary. This is optional, and only\n needed if (1) you are overriding embedding_cls and (2) are doing standard\n pretraining.\n num_hidden_instances: The number of times to instantiate and/or invoke the\n hidden_cls.\n hidden_cls: The class or instance to encode the input data. If hidden_cls is\n not set, a KerasBERT transformer layer will be used as the encoder class.\n hidden_cfg: A dict of kwargs to pass to the hidden_cls, if it needs to be\n instantiated. If hidden_cls is not set, a config dict must be passed to\n 'hidden_cfg' with the following values:\n \"num_attention_heads\": The number of attention heads. The hidden size\n must be divisible by num_attention_heads.\n \"intermediate_size\": The intermediate size of the transformer.\n \"intermediate_activation\": The activation to apply in the transfomer.\n \"dropout_rate\": The overall dropout rate for the transformer layers.\n \"attention_dropout_rate\": The dropout rate for the attention layers.\n \"kernel_initializer\": The initializer for the transformer layers.\n \"dtype\": The dtype of the transformer.\n \"\"\"\n\n def __init__(\n self,\n num_output_classes,\n classification_layer_initializer=tf.keras.initializers.TruncatedNormal(\n stddev=0.02),\n classification_layer_dtype=tf.float32,\n embedding_cls=None,\n embedding_cfg=None,\n embedding_data=None,\n num_hidden_instances=1,\n hidden_cls=layers.Transformer,\n hidden_cfg=None,\n **kwargs):\n print(embedding_cfg)\n self._self_setattr_tracking = False\n self._hidden_cls = hidden_cls\n self._hidden_cfg = hidden_cfg\n self._num_hidden_instances = num_hidden_instances\n self._num_output_classes = num_output_classes\n self._classification_layer_initializer = classification_layer_initializer\n self._embedding_cls = embedding_cls\n self._embedding_cfg = embedding_cfg\n self._embedding_data = embedding_data\n self._kwargs = kwargs\n\n if embedding_cls:\n if inspect.isclass(embedding_cls):\n self._embedding_network = embedding_cls(embedding_cfg)\n else:\n self._embedding_network = embedding_cls\n inputs = self._embedding_network.inputs\n embeddings, mask = self._embedding_network(inputs)\n else:\n self._embedding_network = None\n word_ids = tf.keras.layers.Input(\n shape=(embedding_cfg['seq_length'],),\n dtype=tf.int32,\n name='input_word_ids')\n mask = tf.keras.layers.Input(\n shape=(embedding_cfg['seq_length'],),\n dtype=tf.int32,\n name='input_mask')\n type_ids = tf.keras.layers.Input(\n shape=(embedding_cfg['seq_length'],),\n dtype=tf.int32,\n name='input_type_ids')\n inputs = [word_ids, mask, type_ids]\n\n self._embedding_layer = layers.OnDeviceEmbedding(\n vocab_size=embedding_cfg['vocab_size'],\n embedding_width=embedding_cfg['hidden_size'],\n initializer=embedding_cfg['initializer'],\n name='word_embeddings')\n\n word_embeddings = self._embedding_layer(word_ids)\n\n # Always uses dynamic slicing for simplicity.\n self._position_embedding_layer = layers.PositionEmbedding(\n initializer=embedding_cfg['initializer'],\n use_dynamic_slicing=True,\n max_sequence_length=embedding_cfg['max_seq_length'])\n position_embeddings = self._position_embedding_layer(word_embeddings)\n\n type_embeddings = (\n layers.OnDeviceEmbedding(\n vocab_size=embedding_cfg['type_vocab_size'],\n embedding_width=embedding_cfg['hidden_size'],\n initializer=embedding_cfg['initializer'],\n use_one_hot=True,\n name='type_embeddings')(type_ids))\n\n embeddings = tf.keras.layers.Add()(\n [word_embeddings, position_embeddings, type_embeddings])\n embeddings = (\n tf.keras.layers.LayerNormalization(\n name='embeddings/layer_norm',\n axis=-1,\n epsilon=1e-12,\n dtype=tf.float32)(embeddings))\n embeddings = (\n tf.keras.layers.Dropout(\n rate=embedding_cfg['dropout_rate'], dtype=tf.float32)(embeddings))\n\n if embedding_cfg.get('dtype') == 'float16':\n embeddings = tf.cast(embeddings, tf.float16)\n\n attention_mask = layers.SelfAttentionMask()([embeddings, mask])\n data = embeddings\n\n for _ in range(num_hidden_instances):\n if inspect.isclass(hidden_cls):\n layer = self._hidden_cls(**hidden_cfg)\n else:\n layer = self._hidden_cls\n data = layer([data, attention_mask])\n\n first_token_tensor = (\n tf.keras.layers.Lambda(lambda x: tf.squeeze(x[:, 0:1, :], axis=1))(data)\n )\n cls_output = tf.keras.layers.Dense(\n units=num_output_classes,\n activation='tanh',\n kernel_initializer=classification_layer_initializer,\n dtype=classification_layer_dtype,\n name='cls_transform')(\n first_token_tensor)\n\n super(EncoderScaffold, self).__init__(\n inputs=inputs, outputs=[data, cls_output], **kwargs)\n\n def get_config(self):\n config_dict = {\n 'num_hidden_instances':\n self._num_hidden_instances,\n 'num_output_classes':\n self._num_output_classes,\n 'classification_layer_initializer':\n self._classification_layer_initializer,\n 'embedding_cls':\n self._embedding_network,\n 'embedding_cfg':\n self._embedding_cfg,\n 'hidden_cfg':\n self._hidden_cfg,\n }\n if inspect.isclass(self._hidden_cls):\n config_dict['hidden_cls_string'] = tf.keras.utils.get_registered_name(\n self._hidden_cls)\n else:\n config_dict['hidden_cls'] = self._hidden_cls\n\n config_dict.update(self._kwargs)\n return config_dict\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n if 'hidden_cls_string' in config:\n config['hidden_cls'] = tf.keras.utils.get_registered_object(\n config['hidden_cls_string'], custom_objects=custom_objects)\n del config['hidden_cls_string']\n return cls(**config)\n\n def get_embedding_table(self):\n if self._embedding_network is None:\n # In this case, we don't have a custom embedding network and can return\n # the standard embedding data.\n return self._embedding_layer.embeddings\n\n if self._embedding_data is None:\n raise RuntimeError(('The EncoderScaffold %s does not have a reference '\n 'to the embedding data. This is required when you '\n 'pass a custom embedding network to the scaffold. '\n 'It is also possible that you are trying to get '\n 'embedding data from an embedding scaffold with a '\n 'custom embedding network where the scaffold has '\n 'been serialized and deserialized. Unfortunately, '\n 'accessing custom embedding references after '\n 'serialization is not yet supported.') % self.name)\n else:\n return self._embedding_data\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ==============================================================================\n#\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ==============================================================================\n\nimport tensorflow as tf\n\nfrom model.layers.utils import _log_hparams\n\n__all__ = ['average_pooling2d', 'max_pooling2d']\n\n\ndef average_pooling2d(inputs, pool_size=(2, 2), strides=None, padding='valid', data_format=None, name=\"avg_pooling2d\"):\n\n if data_format not in ['NHWC', 'NCHW']:\n raise ValueError(\"Unknown data format: `%s` (accepted: ['NHWC', 'NCHW'])\" % data_format)\n\n if padding.lower() not in ['same', 'valid']:\n raise ValueError(\"Unknown padding: `%s` (accepted: ['same', 'valid'])\" % padding)\n '''\n net = tf.keras.layers.AveragePooling2D(\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format='channels_first' if data_format == 'NCHW' else 'channels_last',\n name=name,\n )(inputs)\n '''\n\n net = tf.layers.average_pooling2d(\n inputs,\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format='channels_first' if data_format == 'NCHW' else 'channels_last',\n name=name\n )\n\n _log_hparams(\n classname='AveragePooling2D',\n layername=net.name,\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n out_shape=str(net.get_shape())\n )\n\n return net\n\n\ndef max_pooling2d(inputs, pool_size=(2, 2), strides=None, padding='valid', data_format=None, name=\"max_pooling2d\"):\n\n if data_format not in ['NHWC', 'NCHW']:\n raise ValueError(\"Unknown data format: `%s` (accepted: ['NHWC', 'NCHW'])\" % data_format)\n\n if padding.lower() not in ['same', 'valid']:\n raise ValueError(\"Unknown padding: `%s` (accepted: ['same', 'valid'])\" % padding)\n '''\n net = tf.keras.layers.MaxPool2D(\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format='channels_first' if data_format == 'NCHW' else 'channels_last',\n name=name,\n )(inputs)\n '''\n\n net = tf.layers.max_pooling2d(\n inputs,\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format='channels_first' if data_format == 'NCHW' else 'channels_last',\n name=name\n )\n\n _log_hparams(\n classname='MaxPooling2D',\n layername=net.name,\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n out_shape=str(net.get_shape()),\n out_dtype=net.dtype\n )\n\n return net\n", "# Copyright (c) 2018-2019, NVIDIA CORPORATION\n# Copyright (c) 2017- Facebook, Inc\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nimport argparse\nimport random\nfrom copy import deepcopy\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.distributed as dist\nimport torch.nn.parallel\nimport torch.optim\nimport torch.utils.data\nimport torch.utils.data.distributed\n\nfrom image_classification.training import *\nfrom image_classification.utils import *\nfrom image_classification.quantization import *\nfrom image_classification.models import efficientnet_quant_b0, efficientnet_quant_b4\n\nfrom main import prepare_for_training, add_parser_arguments as parse_training\n\nimport dllogger\n\n\ndef available_models():\n models = {\n m.name: m\n for m in [\n efficientnet_quant_b0,\n efficientnet_quant_b4,\n ]\n }\n return models\n\n\ndef parse_quantization(parser):\n model_names = available_models().keys()\n parser.add_argument(\n \"--arch\",\n \"-a\",\n metavar=\"ARCH\",\n default=\"efficientnet-quant-b0\",\n choices=model_names,\n help=\"model architecture: \" + \" | \".join(model_names) + \" (default: efficientnet-quant-b0)\",\n )\n \n parser.add_argument(\n \"--skip-calibration\",\n action=\"store_true\",\n help=\"skip calibration before training, (default: false)\",\n )\n\n\ndef parse_training_args(parser):\n from main import add_parser_arguments\n return add_parser_arguments(parser)\n\n\ndef main(args, model_args, model_arch):\n exp_start_time = time.time()\n global best_prec1\n best_prec1 = 0\n\n skip_calibration = args.skip_calibration or args.evaluate or args.resume is not None\n\n select_default_calib_method()\n\n model_and_loss, optimizer, lr_policy, scaler, train_loader, val_loader, logger, ema, model_ema, train_loader_len, \\\n batch_size_multiplier, start_epoch = prepare_for_training(args, model_args, model_arch)\n \n print(f\"RUNNING QUANTIZATION\")\n \n if not skip_calibration: \n calibrate(model_and_loss.model, train_loader, logger, calib_iter=10)\n \n train_loop(\n model_and_loss,\n optimizer,\n scaler,\n lr_policy,\n train_loader,\n val_loader,\n logger,\n should_backup_checkpoint(args),\n ema=ema,\n model_ema=model_ema,\n steps_per_epoch=train_loader_len,\n use_amp=args.amp,\n batch_size_multiplier=batch_size_multiplier,\n start_epoch=start_epoch,\n end_epoch=min((start_epoch + args.run_epochs), args.epochs)\n if args.run_epochs != -1\n else args.epochs,\n best_prec1=best_prec1,\n prof=args.prof,\n skip_training=args.evaluate,\n skip_validation=args.training_only,\n save_checkpoints=args.save_checkpoints,\n checkpoint_dir=args.workspace,\n checkpoint_filename='quantized_' + args.checkpoint_filename,\n )\n\n if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0:\n logger.end()\n print(\"Experiment ended\")\n\n\nif __name__ == \"__main__\":\n epilog = [\n \"Based on the architecture picked by --arch flag, you may use the following options:\\n\"\n ]\n for model, ep in available_models().items():\n model_help = \"\\n\".join(ep.parser().format_help().split(\"\\n\")[2:])\n epilog.append(model_help)\n parser = argparse.ArgumentParser(\n description=\"PyTorch ImageNet Training\",\n epilog=\"\\n\".join(epilog),\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n\n parse_quantization(parser)\n parse_training(parser, skip_arch=True)\n\n args, rest = parser.parse_known_args()\n \n model_arch = available_models()[args.arch]\n model_args, rest = model_arch.parser().parse_known_args(rest)\n print(model_args)\n\n assert len(rest) == 0, f\"Unknown args passed: {rest}\"\n\n cudnn.benchmark = True\n\n main(args, model_args, model_arch)\n\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\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\nimport sys\n\nimport tensorflow as tf\nimport horovod.tensorflow as hvd\n\nfrom utils import image_processing\nfrom utils import hvd_utils\n\nfrom nvidia import dali\nimport nvidia.dali.plugin.tf as dali_tf\n\n__all__ = [\"get_synth_input_fn\", \"normalized_inputs\"]\n\n\nclass HybridPipe(dali.pipeline.Pipeline):\n\n def __init__(\n self,\n tfrec_filenames,\n tfrec_idx_filenames,\n height,\n width,\n batch_size,\n num_threads,\n device_id,\n shard_id,\n num_gpus,\n deterministic=False,\n dali_cpu=True,\n training=True\n ):\n\n kwargs = dict()\n if deterministic:\n kwargs['seed'] = 7 * (1 + hvd.rank())\n super(HybridPipe, self).__init__(batch_size, num_threads, device_id, **kwargs)\n\n self.training = training\n self.input = dali.ops.TFRecordReader(\n path=tfrec_filenames,\n index_path=tfrec_idx_filenames,\n random_shuffle=True,\n shard_id=shard_id,\n num_shards=num_gpus,\n initial_fill=10000,\n features={\n 'image/encoded': dali.tfrecord.FixedLenFeature((), dali.tfrecord.string, \"\"),\n 'image/class/label': dali.tfrecord.FixedLenFeature([1], dali.tfrecord.int64, -1),\n 'image/class/text': dali.tfrecord.FixedLenFeature([], dali.tfrecord.string, ''),\n 'image/object/bbox/xmin': dali.tfrecord.VarLenFeature(dali.tfrecord.float32, 0.0),\n 'image/object/bbox/ymin': dali.tfrecord.VarLenFeature(dali.tfrecord.float32, 0.0),\n 'image/object/bbox/xmax': dali.tfrecord.VarLenFeature(dali.tfrecord.float32, 0.0),\n 'image/object/bbox/ymax': dali.tfrecord.VarLenFeature(dali.tfrecord.float32, 0.0)\n }\n )\n\n if self.training:\n self.decode = dali.ops.ImageDecoderRandomCrop(\n device=\"cpu\" if dali_cpu else \"mixed\",\n output_type=dali.types.RGB,\n random_aspect_ratio=[0.75, 1.33],\n random_area=[0.05, 1.0],\n num_attempts=100\n )\n self.resize = dali.ops.Resize(device=\"cpu\" if dali_cpu else \"gpu\", resize_x=width, resize_y=height)\n else:\n self.decode = dali.ops.ImageDecoder(device=\"cpu\" if dali_cpu else \"mixed\", output_type=dali.types.RGB)\n # Make sure that every image > 224 for CropMirrorNormalize\n self.resize = dali.ops.Resize(device=\"cpu\" if dali_cpu else \"gpu\", resize_shorter=256)\n\n self.normalize = dali.ops.CropMirrorNormalize(\n device=\"gpu\",\n output_dtype=dali.types.FLOAT,\n crop=(height, width),\n image_type=dali.types.RGB,\n mean=[123.68, 116.28, 103.53],\n std=[58.395, 57.120, 57.385],\n output_layout=dali.types.NHWC\n )\n self.cast_float = dali.ops.Cast(device=\"gpu\", dtype=dali.types.FLOAT)\n self.mirror = dali.ops.CoinFlip()\n self.iter = 0\n\n def define_graph(self):\n # Read images and labels\n inputs = self.input(name=\"Reader\")\n images = inputs[\"image/encoded\"]\n labels = inputs[\"image/class/label\"].gpu()\n\n # Decode and augmentation\n images = self.decode(images)\n images = self.resize(images)\n images = self.normalize(images.gpu(), mirror=self.mirror() if self.training else None)\n\n return (images, labels)\n\n\nclass DALIPreprocessor(object):\n\n def __init__(\n self,\n filenames,\n idx_filenames,\n height,\n width,\n batch_size,\n num_threads,\n dtype=tf.uint8,\n dali_cpu=True,\n deterministic=False,\n training=False\n ):\n device_id = hvd.local_rank()\n shard_id = hvd.rank()\n num_gpus = hvd.size()\n pipe = HybridPipe(\n tfrec_filenames=filenames,\n tfrec_idx_filenames=idx_filenames,\n height=height,\n width=width,\n batch_size=batch_size,\n num_threads=num_threads,\n device_id=device_id,\n shard_id=shard_id,\n num_gpus=num_gpus,\n deterministic=deterministic,\n dali_cpu=dali_cpu,\n training=training\n )\n\n daliop = dali_tf.DALIIterator()\n\n with tf.device(\"/gpu:0\"):\n self.images, self.labels = daliop(\n pipeline=pipe,\n shapes=[(batch_size, height, width, 3), (batch_size, 1)],\n dtypes=[tf.float32, tf.int64],\n device_id=device_id\n )\n\n def get_device_minibatches(self):\n with tf.device(\"/gpu:0\"):\n self.labels -= 1 # Change to 0-based (don't use background class)\n self.labels = tf.squeeze(self.labels, axis=-1)\n return self.images, self.labels\n", "# Copyright (c) 2021 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\nimport torch\n\nfrom dlrm.cuda_ext import dotBasedInteract\n\n\nclass Interaction:\n\n @property\n def num_interactions(self) -> int:\n raise NotImplementedError()\n\n def interact(self, bottom_output, bottom_mlp_output):\n \"\"\"\n :param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]\n :param bottom_mlp_output\n :return:\n \"\"\"\n raise NotImplementedError()\n\n\nclass DotInteraction(Interaction):\n\n def __init__(self, embedding_num: int, embedding_dim: int):\n \"\"\"\n Interactions are among outputs of all the embedding tables and bottom MLP, total number of\n (num_embedding_tables + 1) vectors with size embedding_dim. ``dot`` product interaction computes dot product\n between any 2 vectors. Output of interaction will have shape [num_interactions, embedding_dim].\n \"\"\"\n self._num_interaction_inputs = embedding_num + 1\n self._embedding_dim = embedding_dim\n self._tril_indices = torch.tensor([[i for i in range(self._num_interaction_inputs)\n for _ in range(i)],\n [j for i in range(self._num_interaction_inputs)\n for j in range(i)]])\n\n @property\n def num_interactions(self) -> int:\n n = (self._num_interaction_inputs * (self._num_interaction_inputs - 1)) // 2 + self._embedding_dim\n return n + 1 # pad 1 to be multiple of 8\n\n def interact(self, bottom_output, bottom_mlp_output):\n \"\"\"\n :param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]\n :param bottom_mlp_output\n :return:\n \"\"\"\n batch_size = bottom_output.size()[0]\n\n interaction = torch.bmm(bottom_output, torch.transpose(bottom_output, 1, 2))\n interaction_flat = interaction[:, self._tril_indices[0], self._tril_indices[1]]\n\n # concatenate dense features and interactions\n zeros_padding = torch.zeros(batch_size, 1, dtype=bottom_output.dtype, device=bottom_output.device)\n interaction_output = torch.cat(\n (bottom_mlp_output, interaction_flat, zeros_padding), dim=1)\n\n return interaction_output\n\n\nclass CudaDotInteraction(Interaction):\n\n def __init__(self, dot_interaction: DotInteraction):\n self._dot_interaction = dot_interaction\n\n @property\n def num_interactions(self):\n return self._dot_interaction.num_interactions\n\n def interact(self, bottom_output, bottom_mlp_output):\n \"\"\"\n :param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]\n :param bottom_mlp_output\n :return:\n \"\"\"\n return dotBasedInteract(bottom_output, bottom_mlp_output)\n\n\nclass CatInteraction(Interaction):\n\n def __init__(self, embedding_num: int, embedding_dim: int):\n \"\"\"\n Interactions are among outputs of all the embedding tables and bottom MLP, total number of\n (num_embedding_tables + 1) vectors with size embdding_dim. ``cat`` interaction concatenate all the vectors\n together. Output of interaction will have shape [num_interactions, embedding_dim].\n \"\"\"\n self._num_interaction_inputs = embedding_num + 1\n self._embedding_dim = embedding_dim\n\n @property\n def num_interactions(self) -> int:\n return self._num_interaction_inputs * self._embedding_dim\n\n def interact(self, bottom_output, bottom_mlp_output):\n \"\"\"\n :param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]\n :param bottom_mlp_output\n :return:\n \"\"\"\n return bottom_output.view(-1, self.num_interactions)\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ==============================================================================\n#\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ==============================================================================\n\nimport tensorflow as tf\n\nfrom model.layers.utils import _log_hparams\n\n__all__ = ['concat', 'flatten', 'reshape', 'squeeze', 'upscale_2d']\n\n\ndef concat(values, axis, name='concat'):\n\n net = tf.concat(values=values, axis=axis, name=name)\n\n _log_hparams(classname='Concat', layername=net.name, axis=axis, out_shape=str(net.get_shape()), out_dtype=net.dtype)\n\n return net\n\n\ndef flatten(inputs, name='flatten'):\n\n net = tf.layers.flatten(inputs, name=name)\n\n _log_hparams(classname='Flatten', layername=net.name, out_shape=str(net.get_shape()), out_dtype=net.dtype)\n\n return net\n\n\ndef reshape(tensor, shape, name='reshape'):\n\n net = tf.reshape(tensor, shape=shape, name=name)\n\n _log_hparams(\n classname='Reshape', layername=net.name, shape=shape, out_shape=str(net.get_shape()), out_dtype=net.dtype\n )\n\n return net\n\n\ndef squeeze(tensor, axis, name='squeeze'):\n\n net = tf.squeeze(tensor, axis=axis, name=name)\n\n _log_hparams(\n classname='Squeeze', layername=net.name, axis=axis, out_shape=str(net.get_shape()), out_dtype=net.dtype\n )\n\n return net\n\n\ndef upscale_2d(inputs, size, is_scale=True, method=0, align_corners=True, data_format='NHWC', name='upsample2d_layer'):\n\n if not isinstance(size, (list, tuple)) and len(size) == 2:\n raise AssertionError()\n\n if data_format not in ['NHWC', 'NCHW']:\n raise ValueError(\"Unknown data format received: `%s` (allowed: `NHWC`, `NCHW`)\" % data_format)\n\n input_shape = inputs.get_shape()\n\n if len(inputs.get_shape()) == 3:\n if is_scale:\n size_h = size[0] * int(inputs.get_shape()[0])\n size_w = size[1] * int(inputs.get_shape()[1])\n _size = [size_h, size_w]\n else:\n _size = size\n\n elif len(inputs.get_shape()) == 4:\n if data_format == 'NCHW':\n inputs = tf.transpose(inputs, [0, 2, 3, 1]) # NCHW => NHWC\n\n if is_scale:\n size_h = size[0] * int(inputs.get_shape()[1])\n size_w = size[1] * int(inputs.get_shape()[2])\n _size = [size_h, size_w]\n else:\n _size = size\n\n else:\n raise Exception(\"Do not support shape %s\" % str(inputs.get_shape()))\n\n with tf.variable_scope(name):\n net = tf.image.resize_images(inputs, size=_size, method=method, align_corners=align_corners)\n\n if data_format == 'NCHW' and len(inputs.get_shape()) == 4:\n net = tf.transpose(net, [0, 3, 1, 2]) # NHWC => NCHW\n\n _log_hparams(\n classname='Upscale2D',\n layername=net.name,\n size=size,\n is_scale=is_scale,\n method=method,\n align_corners=align_corners,\n data_format=data_format,\n input_shape=str(input_shape),\n out_shape=str(net.get_shape()),\n out_dtype=net.dtype\n )\n\n return net\n", "\n# Generated by gen_torchvision_benchmark.py\nimport torch\nimport torch.optim as optim\nimport torchvision.models as models\nfrom ...util.model import BenchmarkModel\n\nclass Model(BenchmarkModel):\n def __init__(self, device=None, jit=False):\n super().__init__()\n self.device = device\n self.jit = jit\n self.model = models.mobilenet_v2().to(self.device)\n if self.jit:\n self.model = torch.jit.script(self.model)\n self.example_inputs = (torch.randn((96, 3, 224, 224)).to(self.device),)\n\n def get_module(self):\n return self.model, self.example_inputs\n\n def train(self, niter=3):\n optimizer = optim.Adam(self.model.parameters())\n loss = torch.nn.CrossEntropyLoss()\n for _ in range(niter):\n optimizer.zero_grad()\n pred = self.model(*self.example_inputs)\n y = torch.empty(pred.shape[0], dtype=torch.long, device=self.device).random_(pred.shape[1])\n loss(pred, y).backward()\n optimizer.step()\n\n def eval(self, niter=1):\n model, example_inputs = self.get_module()\n example_inputs = example_inputs[0][0].unsqueeze(0)\n for i in range(niter):\n model(example_inputs)\n\n\nif __name__ == \"__main__\":\n m = Model(device=\"cuda\", jit=True)\n module, example_inputs = m.get_module()\n module(*example_inputs)\n m.train(niter=1)\n m.eval(niter=1)\n\n", "import tensorflow as tf\n\nfrom mrcnn_tf2.model import anchors\nfrom mrcnn_tf2.model.losses import MaskRCNNLoss, FastRCNNLoss, RPNLoss\nfrom mrcnn_tf2.model.models.fpn import FPNNetwork\nfrom mrcnn_tf2.model.models.heads import RPNHead, BoxHead, MaskHead\nfrom mrcnn_tf2.model.models.resnet50 import ResNet50\nfrom mrcnn_tf2.ops import roi_ops, spatial_transform_ops, postprocess_ops, training_ops\n\n\nclass MaskRCNN(tf.keras.Model):\n\n def __init__(self, params, name='mrcnn', trainable=True, *args, **kwargs):\n super().__init__(name=name, trainable=trainable, *args, **kwargs)\n self._params = params\n\n self.backbone = ResNet50()\n\n self.fpn = FPNNetwork(\n min_level=self._params.min_level,\n max_level=self._params.max_level,\n trainable=trainable\n )\n\n self.rpn_head = RPNHead(\n name=\"rpn_head\",\n num_anchors=len(self._params.aspect_ratios * self._params.num_scales),\n trainable=trainable\n )\n\n self.box_head = BoxHead(\n num_classes=self._params.num_classes,\n mlp_head_dim=self._params.fast_rcnn_mlp_head_dim,\n trainable=trainable\n )\n\n self.mask_head = MaskHead(\n num_classes=self._params.num_classes,\n mrcnn_resolution=self._params.mrcnn_resolution,\n trainable=trainable,\n name=\"mask_head\"\n )\n\n self.mask_rcnn_loss = MaskRCNNLoss()\n\n self.fast_rcnn_loss = FastRCNNLoss(\n num_classes=self._params.num_classes\n )\n\n self.rpn_loss = RPNLoss(\n batch_size=self._params.train_batch_size,\n rpn_batch_size_per_im=self._params.rpn_batch_size_per_im,\n min_level=self._params.min_level,\n max_level=self._params.max_level\n )\n\n def call(self, inputs, training=None, mask=None):\n\n batch_size, image_height, image_width, _ = inputs['images'].get_shape().as_list()\n\n if 'source_ids' not in inputs:\n inputs['source_ids'] = -1 * tf.ones([batch_size], dtype=tf.float32)\n\n outputs = dict(inputs)\n\n all_anchors = anchors.Anchors(self._params.min_level, self._params.max_level,\n self._params.num_scales, self._params.aspect_ratios,\n self._params.anchor_scale,\n (image_height, image_width))\n\n backbone_feats = self.backbone(inputs['images'], training=training)\n\n fpn_feats = self.fpn(backbone_feats, training=training)\n\n outputs.update({'fpn_features': fpn_feats})\n\n def rpn_head_fn(features, min_level=2, max_level=6):\n \"\"\"Region Proposal Network (RPN) for Mask-RCNN.\"\"\"\n scores_outputs = dict()\n box_outputs = dict()\n\n for level in range(min_level, max_level + 1):\n scores_outputs[level], box_outputs[level] = self.rpn_head(features[level], training=training)\n\n return scores_outputs, box_outputs\n\n rpn_score_outputs, rpn_box_outputs = rpn_head_fn(\n features=fpn_feats,\n min_level=self._params.min_level,\n max_level=self._params.max_level\n )\n\n if training:\n rpn_pre_nms_topn = self._params.train_rpn_pre_nms_topn\n rpn_post_nms_topn = self._params.train_rpn_post_nms_topn\n rpn_nms_threshold = self._params.train_rpn_nms_threshold\n\n else:\n rpn_pre_nms_topn = self._params.test_rpn_pre_nms_topn\n rpn_post_nms_topn = self._params.test_rpn_post_nms_topn\n rpn_nms_threshold = self._params.test_rpn_nms_thresh\n\n rpn_box_scores, rpn_box_rois = roi_ops.multilevel_propose_rois(\n scores_outputs=rpn_score_outputs,\n box_outputs=rpn_box_outputs,\n all_anchors=all_anchors,\n image_info=inputs['image_info'],\n rpn_pre_nms_topn=rpn_pre_nms_topn,\n rpn_post_nms_topn=rpn_post_nms_topn,\n rpn_nms_threshold=rpn_nms_threshold,\n rpn_min_size=self._params.rpn_min_size,\n bbox_reg_weights=None\n )\n\n rpn_box_rois = tf.cast(rpn_box_rois, dtype=tf.float32)\n\n if training:\n rpn_box_rois = tf.stop_gradient(rpn_box_rois)\n rpn_box_scores = tf.stop_gradient(rpn_box_scores) # TODO Jonathan: Unused => Shall keep ?\n\n # Sampling\n box_targets, class_targets, rpn_box_rois, proposal_to_label_map = training_ops.proposal_label_op(\n rpn_box_rois,\n inputs['gt_boxes'],\n inputs['gt_classes'],\n batch_size_per_im=self._params.batch_size_per_im,\n fg_fraction=self._params.fg_fraction,\n fg_thresh=self._params.fg_thresh,\n bg_thresh_hi=self._params.bg_thresh_hi,\n bg_thresh_lo=self._params.bg_thresh_lo\n )\n\n # Performs multi-level RoIAlign.\n box_roi_features = spatial_transform_ops.multilevel_crop_and_resize(\n features=fpn_feats,\n boxes=rpn_box_rois,\n output_size=7,\n training=training\n )\n\n class_outputs, box_outputs, _ = self.box_head(inputs=box_roi_features)\n\n if not training:\n detections = postprocess_ops.generate_detections_gpu(\n class_outputs=class_outputs,\n box_outputs=box_outputs,\n anchor_boxes=rpn_box_rois,\n image_info=inputs['image_info'],\n pre_nms_num_detections=self._params.test_rpn_post_nms_topn,\n post_nms_num_detections=self._params.test_detections_per_image,\n nms_threshold=self._params.test_nms,\n bbox_reg_weights=self._params.bbox_reg_weights\n )\n\n outputs.update({\n 'num_detections': detections[0],\n 'detection_boxes': detections[1],\n 'detection_classes': detections[2],\n 'detection_scores': detections[3],\n })\n\n else: # is training\n encoded_box_targets = training_ops.encode_box_targets(\n boxes=rpn_box_rois,\n gt_boxes=box_targets,\n gt_labels=class_targets,\n bbox_reg_weights=self._params.bbox_reg_weights\n )\n\n outputs.update({\n 'rpn_score_outputs': rpn_score_outputs,\n 'rpn_box_outputs': rpn_box_outputs,\n 'class_outputs': class_outputs,\n 'box_outputs': box_outputs,\n 'class_targets': class_targets,\n 'box_targets': encoded_box_targets,\n 'box_rois': rpn_box_rois,\n })\n\n # Faster-RCNN mode.\n if not self._params.include_mask:\n return outputs\n\n # Mask sampling\n if not training:\n selected_box_rois = outputs['detection_boxes']\n class_indices = outputs['detection_classes']\n\n else:\n selected_class_targets, selected_box_targets, \\\n selected_box_rois, proposal_to_label_map = training_ops.select_fg_for_masks(\n class_targets=class_targets,\n box_targets=box_targets,\n boxes=rpn_box_rois,\n proposal_to_label_map=proposal_to_label_map,\n max_num_fg=int(self._params.batch_size_per_im * self._params.fg_fraction)\n )\n\n class_indices = tf.cast(selected_class_targets, dtype=tf.int32)\n\n mask_roi_features = spatial_transform_ops.multilevel_crop_and_resize(\n features=fpn_feats,\n boxes=selected_box_rois,\n output_size=14,\n training=training\n )\n\n mask_outputs = self.mask_head(\n inputs=(mask_roi_features, class_indices),\n training=training\n )\n\n if training:\n mask_targets = training_ops.get_mask_targets(\n\n fg_boxes=selected_box_rois,\n fg_proposal_to_label_map=proposal_to_label_map,\n fg_box_targets=selected_box_targets,\n mask_gt_labels=inputs['cropped_gt_masks'],\n output_size=self._params.mrcnn_resolution\n )\n\n outputs.update({\n 'mask_outputs': mask_outputs,\n 'mask_targets': mask_targets,\n 'selected_class_targets': selected_class_targets,\n })\n\n else:\n outputs.update({\n 'detection_masks': tf.nn.sigmoid(mask_outputs),\n })\n\n if training:\n self._add_losses(outputs)\n\n # filter out only the needed outputs\n model_outputs = [\n 'source_ids', 'image_info',\n 'num_detections', 'detection_boxes',\n 'detection_classes', 'detection_scores',\n 'detection_masks'\n ]\n return {\n name: tf.identity(tensor, name=name)\n for name, tensor in outputs.items()\n if name in model_outputs\n }\n\n def _add_losses(self, model_outputs):\n mask_rcnn_loss = self.mask_rcnn_loss(model_outputs)\n mask_rcnn_loss *= self._params.mrcnn_weight_loss_mask\n self.add_loss(mask_rcnn_loss)\n self.add_metric(mask_rcnn_loss, name='mask_rcnn_loss')\n\n fast_rcnn_class_loss, fast_rcnn_box_loss = self.fast_rcnn_loss(model_outputs)\n fast_rcnn_box_loss *= self._params.fast_rcnn_box_loss_weight\n self.add_loss(fast_rcnn_box_loss)\n self.add_metric(fast_rcnn_box_loss, name='fast_rcnn_box_loss')\n self.add_loss(fast_rcnn_class_loss)\n self.add_metric(fast_rcnn_class_loss, name='fast_rcnn_class_loss')\n\n rpn_score_loss, rpn_box_loss = self.rpn_loss(model_outputs)\n rpn_box_loss *= self._params.rpn_box_loss_weight\n self.add_loss(rpn_box_loss)\n self.add_metric(rpn_box_loss, name='rpn_box_loss')\n self.add_loss(rpn_score_loss)\n self.add_metric(rpn_score_loss, name='rpn_score_loss')\n\n l2_regularization_loss = tf.add_n([\n tf.nn.l2_loss(tf.cast(v, dtype=tf.float32))\n for v in self.trainable_variables\n if not any([pattern in v.name for pattern in [\"batch_normalization\", \"bias\", \"beta\"]])\n ])\n l2_regularization_loss *= self._params.l2_weight_decay\n self.add_loss(l2_regularization_loss)\n self.add_metric(l2_regularization_loss, name='l2_regularization_loss')\n\n def get_config(self):\n pass\n" ]
[ [ "pandas.read_parquet" ], [ "tensorflow.reduce_max", "tensorflow.multiply", "tensorflow.greater", "tensorflow.shape", "tensorflow.cast", "tensorflow.ones", "tensorflow.one_hot", "tensorflow.where", "tensorflow.argmax", "tensorflow.greater_equal" ], [ "tensorflow.keras.layers.LayerNormalization", "tensorflow.keras.layers.Dropout", "tensorflow.keras.utils.get_registered_name", "tensorflow.keras.layers.Dense", "tensorflow.cast", "tensorflow.keras.utils.register_keras_serializable", "tensorflow.squeeze", "tensorflow.keras.layers.Add", "tensorflow.keras.utils.get_registered_object", "tensorflow.keras.initializers.TruncatedNormal", "tensorflow.keras.layers.Input" ], [ "tensorflow.layers.max_pooling2d", "tensorflow.layers.average_pooling2d" ], [ "torch.distributed.get_rank", "torch.distributed.is_initialized" ], [ "tensorflow.device", "tensorflow.squeeze" ], [ "torch.transpose", "torch.cat", "torch.zeros" ], [ "tensorflow.layers.flatten", "tensorflow.concat", "tensorflow.transpose", "tensorflow.image.resize_images", "tensorflow.reshape", "tensorflow.squeeze", "tensorflow.variable_scope" ], [ "torch.jit.script", "torch.randn", "torch.nn.CrossEntropyLoss", "torch.empty" ], [ "tensorflow.nn.sigmoid", "tensorflow.cast", "tensorflow.identity", "tensorflow.ones", "tensorflow.stop_gradient" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "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" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
jklymak/dolfyn
[ "eea98fe0021886cf654e25293c385c5c3707ff8d", "eea98fe0021886cf654e25293c385c5c3707ff8d" ]
[ "dolfyn/io/rdi.py", "docs/examples/adv_motion_correction2.py" ]
[ "import numpy as np\nimport xarray as xr\nfrom .. import time as tmlib\nimport warnings\nfrom os.path import getsize\nfrom ._read_bin import bin_reader\nfrom .base import _find_userdata, _create_dataset, _abspath\nfrom ..rotate.rdi import _calc_beam_orientmat, _calc_orientmat\nfrom ..rotate.base import _set_coords\nfrom ..rotate.api import set_declination\n\n\ndef read_rdi(fname, userdata=None, nens=None, debug=0):\n \"\"\"Read a TRDI binary data file.\n\n Parameters\n ----------\n filename : string\n Filename of TRDI file to read.\n userdata : True, False, or string of userdata.json filename (default ``True``) \n Whether to read the '<base-filename>.userdata.json' file.\n nens : None (default: read entire file), int, or 2-element tuple (start, stop)\n Number of pings to read from the file\n\n Returns\n -------\n ds : xarray.Dataset\n An xarray dataset from the binary instrument data\n\n \"\"\"\n # Reads into a dictionary of dictionaries using netcdf naming conventions\n # Should be easier to debug\n with _RdiReader(fname, debug_level=debug) as ldr:\n dat = ldr.load_data(nens=nens)\n\n # Read in userdata\n userdata = _find_userdata(fname, userdata)\n for nm in userdata:\n dat['attrs'][nm] = userdata[nm]\n\n if 'time_gps' in dat['coords']:\n # GPS data not necessarily sampling at the same rate as ADCP DAQ.\n dat = _remove_gps_duplicates(dat)\n\n # Create xarray dataset from upper level dictionary\n ds = _create_dataset(dat)\n ds = _set_coords(ds, ref_frame=ds.coord_sys)\n\n # Create orientation matrices\n if 'beam2inst_orientmat' not in ds:\n ds['beam2inst_orientmat'] = xr.DataArray(_calc_beam_orientmat(\n ds.beam_angle,\n ds.beam_pattern == 'convex'),\n coords={'x': [1, 2, 3, 4],\n 'x*': [1, 2, 3, 4]},\n dims=['x', 'x*'])\n\n if 'orientmat' not in ds:\n ds['orientmat'] = xr.DataArray(_calc_orientmat(ds),\n coords={'earth': ['E', 'N', 'U'],\n 'inst': ['X', 'Y', 'Z'],\n 'time': ds['time']},\n dims=['earth', 'inst', 'time'])\n\n # Check magnetic declination if provided via software and/or userdata\n _set_rdi_declination(ds, fname, inplace=True)\n\n # VMDAS applies gps correction on velocity in .ENX files only\n if fname.rsplit('.')[-1] == 'ENX':\n ds.attrs['vel_gps_corrected'] = 1\n else: # (not ENR or ENS) or WinRiver files\n ds.attrs['vel_gps_corrected'] = 0\n\n # Convert time coords to dt64\n t_coords = [t for t in ds.coords if 'time' in t]\n for ky in t_coords:\n dt = tmlib.epoch2dt64(ds[ky])\n ds = ds.assign_coords({ky: dt})\n\n # Convert time vars to dt64\n t_data = [t for t in ds.data_vars if 'time' in t]\n for ky in t_data:\n dt = tmlib.epoch2dt64(ds[ky])\n ds[ky].data = dt\n\n return ds\n\n\ndef _remove_gps_duplicates(dat):\n \"\"\"\n Removes duplicate and nan timestamp values in 'time_gps' coordinate, and \n ads hardware (ADCP DAQ) timestamp corresponding to GPS acquisition\n (in addition to the GPS unit's timestamp).\n \"\"\"\n\n dat['data_vars']['hdwtime_gps'] = dat['coords']['time']\n dat['units']['hdwtime'] = 'seconds since 1970-01-01 00:00:00'\n\n # Remove duplicate timestamp values, if applicable\n dat['coords']['time_gps'], idx = np.unique(dat['coords']['time_gps'],\n return_index=True)\n # Remove nan values, if applicable\n nan = np.zeros(dat['coords']['time'].shape, dtype=bool)\n if any(np.isnan(dat['coords']['time_gps'])):\n nan = np.isnan(dat['coords']['time_gps'])\n dat['coords']['time_gps'] = dat['coords']['time_gps'][~nan]\n\n for key in dat['data_vars']:\n if 'gps' in key:\n dat['data_vars'][key] = dat['data_vars'][key][idx]\n if sum(nan) > 0:\n dat['data_vars'][key] = dat['data_vars'][key][~nan]\n\n return dat\n\n\ndef _set_rdi_declination(dat, fname, inplace):\n # If magnetic_var_deg is set, this means that the declination is already\n # included in the heading and in the velocity data.\n\n declin = dat.attrs.pop('declination', None) # userdata declination\n\n if dat.attrs['magnetic_var_deg'] != 0: # from TRDI software if set\n dat.attrs['declination'] = dat.attrs['magnetic_var_deg']\n dat.attrs['declination_in_orientmat'] = 1 # logical\n\n if dat.attrs['magnetic_var_deg'] != 0 and declin is not None:\n warnings.warn(\n \"'magnetic_var_deg' is set to {:.2f} degrees in the binary \"\n \"file '{}', AND 'declination' is set in the 'userdata.json' \"\n \"file. DOLfYN WILL USE THE VALUE of {:.2f} degrees in \"\n \"userdata.json. If you want to use the value in \"\n \"'magnetic_var_deg', delete the value from userdata.json and \"\n \"re-read the file.\"\n .format(dat.attrs['magnetic_var_deg'], fname, declin))\n dat.attrs['declination'] = declin\n\n if declin is not None:\n set_declination(dat, declin, inplace)\n\n\ncentury = 2000\ndata_defs = {'number': ([], 'data_vars', 'uint32', ''),\n 'rtc': ([7], 'sys', 'uint16', ''),\n 'builtin_test_fail': ([], 'data_vars', 'bool', ''),\n 'c_sound': ([], 'data_vars', 'float32', 'm/s'),\n 'depth': ([], 'data_vars', 'float32', 'm'),\n 'pitch': ([], 'data_vars', 'float32', 'deg'),\n 'roll': ([], 'data_vars', 'float32', 'deg'),\n 'heading': ([], 'data_vars', 'float32', 'deg'),\n 'temp': ([], 'data_vars', 'float32', 'C'),\n 'salinity': ([], 'data_vars', 'float32', 'psu'),\n 'min_preping_wait': ([], 'data_vars', 'float32', 's'),\n 'heading_std': ([], 'data_vars', 'float32', 'deg'),\n 'pitch_std': ([], 'data_vars', 'float32', 'deg'),\n 'roll_std': ([], 'data_vars', 'float32', 'deg'),\n 'adc': ([8], 'sys', 'uint8', ''),\n 'error_status_wd': ([], 'attrs', 'float32', ''),\n 'pressure': ([], 'data_vars', 'float32', 'dbar'),\n 'pressure_std': ([], 'data_vars', 'float32', 'dbar'),\n 'vel': (['nc', 4], 'data_vars', 'float32', 'm/s'),\n 'amp': (['nc', 4], 'data_vars', 'uint8', 'counts'),\n 'corr': (['nc', 4], 'data_vars', 'uint8', 'counts'),\n 'prcnt_gd': (['nc', 4], 'data_vars', 'uint8', '%'),\n 'status': (['nc', 4], 'data_vars', 'float32', ''),\n 'dist_bt': ([4], 'data_vars', 'float32', 'm'),\n 'vel_bt': ([4], 'data_vars', 'float32', 'm/s'),\n 'corr_bt': ([4], 'data_vars', 'uint8', 'counts'),\n 'amp_bt': ([4], 'data_vars', 'uint8', 'counts'),\n 'prcnt_gd_bt': ([4], 'data_vars', 'uint8', '%'),\n 'time': ([], 'coords', 'float64', ''),\n 'etime_gps': ([], 'coords', 'float64', ''),\n 'elatitude_gps': ([], 'data_vars', 'float64', 'deg'),\n 'elongitude_gps': ([], 'data_vars', 'float64', 'deg'),\n 'time_gps': ([], 'coords', 'float64', ''),\n 'latitude_gps': ([], 'data_vars', 'float64', 'deg'),\n 'longitude_gps': ([], 'data_vars', 'float64', 'deg'),\n 'ntime': ([], 'coords', 'float64', ''),\n 'flags': ([], 'data_vars', 'float32', ''),\n }\n\n\ndef _get(dat, nm):\n grp = data_defs[nm][1]\n if grp is None:\n return dat[nm]\n else:\n return dat[grp][nm]\n\n\ndef _in_group(dat, nm):\n grp = data_defs[nm][1]\n if grp is None:\n return nm in dat\n else:\n return nm in dat[grp]\n\n\ndef _pop(dat, nm):\n grp = data_defs[nm][1]\n if grp is None:\n dat.pop(nm)\n else:\n dat[grp].pop(nm)\n\n\ndef _setd(dat, nm, val):\n grp = data_defs[nm][1]\n if grp is None:\n dat[nm] = val\n else:\n dat[grp][nm] = val\n\n\ndef _idata(dat, nm, sz):\n group = data_defs[nm][1]\n dtype = data_defs[nm][2]\n units = data_defs[nm][3]\n arr = np.empty(sz, dtype=dtype)\n if dtype.startswith('float'):\n arr[:] = np.NaN\n dat[group][nm] = arr\n dat['units'][nm] = units\n return dat\n\n\ndef _get_size(name, n=None, ncell=0):\n sz = list(data_defs[name][0]) # create a copy!\n if 'nc' in sz:\n sz.insert(sz.index('nc'), ncell)\n sz.remove('nc')\n if n is None:\n return tuple(sz)\n return tuple(sz + [n])\n\n\nclass _variable_setlist(set):\n def __iadd__(self, vals):\n if vals[0] not in self:\n self |= set(vals)\n return self\n\n\nclass _ensemble():\n n_avg = 1\n k = -1 # This is the counter for filling the ensemble object\n\n def __getitem__(self, nm):\n return getattr(self, nm)\n\n def __init__(self, navg, n_cells):\n if navg is None or navg == 0:\n navg = 1\n self.n_avg = navg\n for nm in data_defs:\n setattr(self, nm,\n np.zeros(_get_size(nm, n=navg, ncell=n_cells),\n dtype=data_defs[nm][2]))\n\n def clean_data(self,):\n self['vel'][self['vel'] == -32.768] = np.NaN\n\n\nclass _RdiReader():\n _n_beams = 4 # Placeholder for 5-beam adcp, not currently used.\n _pos = 0\n progress = 0\n _cfgnames = dict.fromkeys([4, 5], 'bb-adcp')\n _cfgnames.update(dict.fromkeys([8, 9, 16], 'wh-adcp'))\n _cfgnames.update(dict.fromkeys([14, 23], 'os-adcp'))\n _cfac = 180 / 2 ** 31\n _source = 0\n _fixoffset = 0\n _nbyte = 0\n _winrivprob = False\n _search_num = 30000 # Maximum distance? to search\n _debug7f79 = None\n extrabytes = 0\n\n def __init__(self, fname, navg=1, debug_level=0):\n self.fname = _abspath(fname)\n print('\\nReading file {} ...'.format(fname))\n self._debug_level = debug_level\n self.cfg = {}\n self.cfg['name'] = 'wh-adcp'\n self.cfg['sourceprog'] = 'instrument'\n self.cfg['prog_ver'] = 0\n self.hdr = {}\n self.f = bin_reader(self.fname)\n self.read_hdr()\n self.read_cfg()\n self.f.seek(self._pos, 0)\n self.n_avg = navg\n self.ensemble = _ensemble(self.n_avg, self.cfg['n_cells'])\n self._filesize = getsize(self.fname)\n self._npings = int(self._filesize / (self.hdr['nbyte'] + 2 +\n self.extrabytes))\n self.vars_read = _variable_setlist(['time'])\n\n if self._debug_level > 0:\n print(' %d pings estimated in this file' % self._npings)\n\n def read_hdr(self,):\n fd = self.f\n cfgid = list(fd.read_ui8(2))\n nread = 0\n if self._debug_level > 2:\n print(self.f.pos)\n print(' cfgid0: [{:x}, {:x}]'.format(*cfgid))\n while (cfgid[0] != 127 or cfgid[1] != 127) or not self.checkheader():\n nextbyte = fd.read_ui8(1)\n pos = fd.tell()\n nread += 1\n cfgid[1] = cfgid[0]\n cfgid[0] = nextbyte\n if not pos % 1000:\n print(' Still looking for valid cfgid at file '\n 'position %d ...' % pos)\n self._pos = self.f.tell() - 2\n if self._debug_level > 0:\n print(fd.tell())\n self.read_hdrseg()\n\n def read_cfg(self,):\n cfgid = self.f.read_ui16(1)\n self.read_cfgseg()\n\n def init_data(self,):\n outd = {'data_vars': {}, 'coords': {},\n 'attrs': {}, 'units': {}, 'sys': {}}\n outd['attrs']['inst_make'] = 'TRDI'\n outd['attrs']['inst_model'] = 'Workhorse'\n outd['attrs']['inst_type'] = 'ADCP'\n outd['attrs']['rotate_vars'] = ['vel', ]\n # Currently RDI doesn't use IMUs\n outd['attrs']['has_imu'] = 0\n for nm in data_defs:\n outd = _idata(outd, nm,\n sz=_get_size(nm, self._nens, self.cfg['n_cells']))\n self.outd = outd\n\n def mean(self, dat):\n if self.n_avg == 1:\n return dat[..., 0]\n return np.nanmean(dat, axis=-1)\n\n def load_data(self, nens=None):\n if nens is None:\n self._nens = int(self._npings / self.n_avg)\n self._ens_range = (0, self._nens)\n elif (nens.__class__ is tuple or nens.__class__ is list) and \\\n len(nens) == 2:\n nens = list(nens)\n if nens[1] == -1:\n nens[1] = self._npings\n self._nens = int((nens[1] - nens[0]) / self.n_avg)\n self._ens_range = nens\n self.f.seek((self.hdr['nbyte'] + 2 + self.extrabytes) *\n self._ens_range[0], 1)\n else:\n self._nens = nens\n self._ens_range = (0, nens)\n if self._debug_level > 0:\n print(' taking data from pings %d - %d' % tuple(self._ens_range))\n print(' %d ensembles will be produced.' % self._nens)\n self.init_data()\n dat = self.outd\n dat['coords']['range'] = (self.cfg['bin1_dist_m'] +\n np.arange(self.cfg['n_cells']) *\n self.cfg['cell_size'])\n for nm in self.cfg:\n dat['attrs'][nm] = self.cfg[nm]\n for iens in range(self._nens):\n try:\n self.read_buffer()\n except:\n self.remove_end(iens)\n break\n self.ensemble.clean_data()\n # Fix the 'real-time-clock' century\n clock = self.ensemble.rtc[:, :]\n if clock[0, 0] < 100:\n clock[0, :] += century\n # Copy the ensemble to the dataset.\n for nm in self.vars_read:\n _get(dat, nm)[..., iens] = self.mean(self.ensemble[nm])\n try:\n dats = tmlib.date2epoch(\n tmlib.datetime(*clock[:6, 0],\n microsecond=clock[6, 0] * 10000))[0]\n except ValueError:\n warnings.warn(\"Invalid time stamp in ping {}.\".format(\n int(self.ensemble.number[0])))\n dat['coords']['time'][iens] = np.NaN\n else:\n dat['coords']['time'][iens] = np.median(dats)\n self.finalize()\n if 'vel_bt' in dat['data_vars']:\n dat['attrs']['rotate_vars'].append('vel_bt')\n return dat\n\n def read_buffer(self,):\n fd = self.f\n self.ensemble.k = -1 # so that k+=1 gives 0 on the first loop.\n self.print_progress()\n hdr = self.hdr\n while self.ensemble.k < self.ensemble.n_avg - 1:\n self.search_buffer()\n startpos = fd.tell() - 2\n self.read_hdrseg()\n byte_offset = self._nbyte + 2\n for n in range(len(hdr['dat_offsets'])):\n id = fd.read_ui16(1)\n self._winrivprob = False\n self.print_pos()\n retval = self.read_dat(id)\n if retval == 'FAIL':\n break\n byte_offset += self._nbyte\n if n < (len(hdr['dat_offsets']) - 1):\n oset = hdr['dat_offsets'][n + 1] - byte_offset\n if oset != 0:\n if self._debug_level > 0:\n print(' %s: Adjust location by %d\\n' % (id, oset))\n fd.seek(oset, 1)\n byte_offset = hdr['dat_offsets'][n + 1]\n else:\n if hdr['nbyte'] - 2 != byte_offset:\n if not self._winrivprob:\n if self._debug_level > 0:\n print(' {:d}: Adjust location by {:d}\\n'\n .format(id, hdr['nbyte'] - 2 - byte_offset))\n self.f.seek(hdr['nbyte'] - 2 - byte_offset, 1)\n byte_offset = hdr['nbyte'] - 2\n readbytes = fd.tell() - startpos\n offset = hdr['nbyte'] + 2 - byte_offset\n self.check_offset(offset, readbytes)\n self.print_pos(byte_offset=byte_offset)\n\n def search_buffer(self):\n \"\"\"\n Check to see if the next bytes indicate the beginning of a\n data block. If not, search for the next data block, up to\n _search_num times.\n \"\"\"\n id1 = list(self.f.read_ui8(2))\n search_cnt = 0\n fd = self.f\n if self._debug_level > 3:\n print(' -->In search_buffer...')\n while (search_cnt < self._search_num and\n ((id1[0] != 127 or id1[1] != 127) or\n not self.checkheader())):\n search_cnt += 1\n nextbyte = fd.read_ui8(1)\n id1[1] = id1[0]\n id1[0] = nextbyte\n if search_cnt == self._search_num:\n raise Exception(\n 'Searched {} entries... Bad data encountered. -> {}'\n .format(search_cnt, id1))\n elif search_cnt > 0:\n if self._debug_level > 0:\n print(' WARNING: Searched {} bytes to find next '\n 'valid ensemble start [{:x}, {:x}]'.format(search_cnt,\n *id1))\n\n def checkheader(self,):\n if self._debug_level > 1:\n print(\" ###In checkheader.\")\n fd = self.f\n valid = 0\n # print(self.f.pos)\n numbytes = fd.read_i16(1)\n if numbytes > 0:\n fd.seek(numbytes - 2, 1)\n cfgid = fd.read_ui8(2)\n if len(cfgid) == 2:\n fd.seek(-numbytes - 2, 1)\n if cfgid[0] == 127 and cfgid[1] in [127, 121]:\n if cfgid[1] == 121 and self._debug7f79 is None:\n self._debug7f79 = True\n valid = 1\n else:\n fd.seek(-2, 1)\n if self._debug_level > 1:\n print(\" ###Leaving checkheader.\")\n return valid\n\n def read_hdrseg(self,):\n fd = self.f\n hdr = self.hdr\n hdr['nbyte'] = fd.read_i16(1)\n if self._debug_level > 2:\n print(fd.tell())\n fd.seek(1, 1)\n ndat = fd.read_i8(1)\n hdr['dat_offsets'] = fd.read_i16(ndat)\n self._nbyte = 4 + ndat * 2\n\n def print_progress(self,):\n self.progress = self.f.tell()\n if self._debug_level > 1:\n print(' pos %0.0fmb/%0.0fmb\\n' %\n (self.f.tell() / 1048576., self._filesize / 1048576.))\n if (self.f.tell() - self.progress) < 1048576:\n return\n\n def print_pos(self, byte_offset=-1):\n \"\"\"Print the position in the file, used for debugging.\n \"\"\"\n if self._debug_level > 3:\n if hasattr(self, 'ensemble'):\n k = self.ensemble.k\n else:\n k = 0\n print(' pos: %d, pos_: %d, nbyte: %d, k: %d, byte_offset: %d' %\n (self.f.tell(), self._pos, self._nbyte, k, byte_offset))\n\n def check_offset(self, offset, readbytes):\n fd = self.f\n if offset != 4 and self._fixoffset == 0:\n if self._debug_level >= 1:\n print('\\n ********************************************\\n')\n if fd.tell() == self._filesize:\n print(' EOF reached unexpectedly - discarding this last ensemble\\n')\n else:\n print(\" Adjust location by {:d} (readbytes={:d},hdr['nbyte']={:d}\\n\"\n .format(offset, readbytes, self.hdr['nbyte']))\n print(\"\"\"\n NOTE - If this appears at the beginning of the file, it may be\n a dolfyn problem. Please report this message, with details here:\n https://github.com/lkilcher/dolfyn/issues/8\n\n - If this appears at the end of the file it means\n The file is corrupted and only a partial record\n has been read\\n\n \"\"\")\n print('\\n ********************************************\\n')\n self._fixoffset = offset - 4\n fd.seek(4 + self._fixoffset, 1)\n\n def read_dat(self, id):\n function_map = {0: (self.read_fixed, []), # 0000\n 128: (self.read_var, []), # 0080\n 256: (self.read_vel, []), # 0100\n 512: (self.read_corr, []), # 0200\n 768: (self.read_amp, []), # 0300\n 1024: (self.read_prcnt_gd, []), # 0400\n 1280: (self.read_status, []), # 0500\n 1536: (self.read_bottom, []), # 0600\n 8192: (self.read_vmdas, []), # 2000\n 8226: (self.read_winriver2, []), # 2022\n 8448: (self.read_winriver, [38]), # 2100\n 8449: (self.read_winriver, [97]), # 2101\n 8450: (self.read_winriver, [45]), # 2102\n 8451: (self.read_winriver, [60]), # 2103\n 8452: (self.read_winriver, [38]), # 2104\n # Loading of these data is currently not implemented:\n 1793: (self.skip_Ncol, [4]), # 0701 number of pings\n 1794: (self.skip_Ncol, [4]), # 0702 sum of squared vel\n 1795: (self.skip_Ncol, [4]), # 0703 sum of velocities\n 2560: (self.skip_Ncol, []), # 0A00 Beam 5 velocity\n # 0301 Beam 5 Number of good pings\n 769: (self.skip_Ncol, []),\n # 0302 Beam 5 Sum of squared velocities\n 770: (self.skip_Ncol, []),\n # 0303 Beam 5 Sum of velocities\n 771: (self.skip_Ncol, []),\n # 020C Ambient sound profile\n 524: (self.skip_Nbyte, [4]),\n 12288: (self.skip_Nbyte, [32]),\n # 3000 Fixed attitude data format for OS-ADCPs\n }\n # Call the correct function:\n if id in function_map:\n if self._debug_level >= 2:\n print(' Reading code {}...'.format(hex(id)), end='')\n retval = function_map.get(id)[0](*function_map[id][1])\n if retval:\n return retval\n if self._debug_level >= 2:\n print(' success!')\n else:\n self.read_nocode(id)\n\n def read_fixed(self,):\n if hasattr(self, 'configsize'):\n self.f.seek(self.configsize, 1)\n self._nbyte = self.configsize\n else:\n self.read_cfgseg()\n if self._debug_level >= 1:\n print(self._pos)\n self._nbyte += 2\n\n def read_cfgseg(self,):\n cfgstart = self.f.tell()\n cfg = self.cfg\n fd = self.f\n tmp = fd.read_ui8(5)\n prog_ver0 = tmp[0]\n cfg['prog_ver'] = tmp[0] + tmp[1] / 100.\n cfg['name'] = self._cfgnames.get(tmp[0],\n 'unrecognized firmware version')\n config = tmp[2:4]\n cfg['beam_angle'] = [15, 20, 30][(config[1] & 3)]\n #cfg['numbeams'] = [4, 5][int((config[1] & 16) == 16)]\n cfg['freq'] = ([75, 150, 300, 600, 1200, 2400, 38][(config[0] & 7)])\n cfg['beam_pattern'] = (['concave',\n 'convex'][int((config[0] & 8) == 8)])\n cfg['orientation'] = ['down', 'up'][int((config[0] & 128) == 128)]\n #cfg['simflag'] = ['real', 'simulated'][tmp[4]]\n fd.seek(1, 1)\n cfg['n_beams'] = fd.read_ui8(1)\n cfg['n_cells'] = fd.read_ui8(1)\n cfg['pings_per_ensemble'] = fd.read_ui16(1)\n cfg['cell_size'] = fd.read_ui16(1) * .01\n cfg['blank'] = fd.read_ui16(1) * .01\n cfg['prof_mode'] = fd.read_ui8(1)\n cfg['corr_threshold'] = fd.read_ui8(1)\n cfg['prof_codereps'] = fd.read_ui8(1)\n cfg['min_pgood'] = fd.read_ui8(1)\n cfg['evel_threshold'] = fd.read_ui16(1)\n cfg['sec_between_ping_groups'] = (\n np.sum(np.array(fd.read_ui8(3)) *\n np.array([60., 1., .01])))\n coord_sys = fd.read_ui8(1)\n cfg['coord_sys'] = (['beam', 'inst',\n 'ship', 'earth'][((coord_sys >> 3) & 3)])\n cfg['use_pitchroll'] = ['no', 'yes'][(coord_sys & 4) == 4]\n cfg['use_3beam'] = ['no', 'yes'][(coord_sys & 2) == 2]\n cfg['bin_mapping'] = ['no', 'yes'][(coord_sys & 1) == 1]\n cfg['xducer_misalign_deg'] = fd.read_i16(1) * .01\n cfg['magnetic_var_deg'] = fd.read_i16(1) * .01\n cfg['sensors_src'] = np.binary_repr(fd.read_ui8(1), 8)\n cfg['sensors_avail'] = np.binary_repr(fd.read_ui8(1), 8)\n cfg['bin1_dist_m'] = fd.read_ui16(1) * .01\n cfg['xmit_pulse'] = fd.read_ui16(1) * .01\n cfg['water_ref_cells'] = list(fd.read_ui8(2)) # list for attrs\n cfg['fls_target_threshold'] = fd.read_ui8(1)\n fd.seek(1, 1)\n cfg['xmit_lag_m'] = fd.read_ui16(1) * .01\n self._nbyte = 40\n self.configsize = self.f.tell() - cfgstart\n\n def read_var(self,):\n \"\"\" Read variable leader \"\"\"\n fd = self.f\n self.ensemble.k += 1\n ens = self.ensemble\n k = ens.k\n self.vars_read += ['number',\n 'rtc',\n 'number',\n 'builtin_test_fail',\n 'c_sound',\n 'depth',\n 'heading',\n 'pitch',\n 'roll',\n 'salinity',\n 'temp',\n 'min_preping_wait',\n 'heading_std',\n 'pitch_std',\n 'roll_std',\n 'adc']\n ens.number[k] = fd.read_ui16(1)\n ens.rtc[:, k] = fd.read_ui8(7)\n ens.number[k] += 65535 * fd.read_ui8(1)\n ens.builtin_test_fail[k] = fd.read_ui16(1)\n ens.c_sound[k] = fd.read_ui16(1)\n ens.depth[k] = fd.read_ui16(1) * 0.1\n ens.heading[k] = fd.read_ui16(1) * 0.01\n ens.pitch[k] = fd.read_i16(1) * 0.01\n ens.roll[k] = fd.read_i16(1) * 0.01\n ens.salinity[k] = fd.read_i16(1)\n ens.temp[k] = fd.read_i16(1) * 0.01\n ens.min_preping_wait[k] = (fd.read_ui8(\n 3) * np.array([60, 1, .01])).sum()\n ens.heading_std[k] = fd.read_ui8(1)\n ens.pitch_std[k] = fd.read_ui8(1) * 0.1\n ens.roll_std[k] = fd.read_ui8(1) * 0.1\n ens.adc[:, k] = fd.read_i8(8)\n self._nbyte = 2 + 40\n\n def read_vel(self,):\n ens = self.ensemble\n self.vars_read += ['vel']\n k = ens.k\n ens['vel'][:, :, k] = np.array(\n self.f.read_i16(4 * self.cfg['n_cells'])\n ).reshape((self.cfg['n_cells'], 4)) * .001\n self._nbyte = 2 + 4 * self.cfg['n_cells'] * 2\n\n def read_corr(self,):\n k = self.ensemble.k\n self.vars_read += ['corr']\n self.ensemble.corr[:, :, k] = np.array(\n self.f.read_ui8(4 * self.cfg['n_cells'])\n ).reshape((self.cfg['n_cells'], 4))\n self._nbyte = 2 + 4 * self.cfg['n_cells']\n\n def read_amp(self,):\n k = self.ensemble.k\n self.vars_read += ['amp']\n self.ensemble.amp[:, :, k] = np.array(\n self.f.read_ui8(4 * self.cfg['n_cells'])\n ).reshape((self.cfg['n_cells'], 4))\n self._nbyte = 2 + 4 * self.cfg['n_cells']\n\n def read_prcnt_gd(self,):\n self.vars_read += ['prcnt_gd']\n self.ensemble.prcnt_gd[:, :, self.ensemble.k] = np.array(\n self.f.read_ui8(4 * self.cfg['n_cells'])\n ).reshape((self.cfg['n_cells'], 4))\n self._nbyte = 2 + 4 * self.cfg['n_cells']\n\n def read_status(self,):\n self.vars_read += ['status']\n self.ensemble.status[:, :, self.ensemble.k] = np.array(\n self.f.read_ui8(4 * self.cfg['n_cells'])\n ).reshape((self.cfg['n_cells'], 4))\n self._nbyte = 2 + 4 * self.cfg['n_cells']\n\n def read_bottom(self,):\n self.vars_read += ['dist_bt', 'vel_bt', 'corr_bt', 'amp_bt',\n 'prcnt_gd_bt']\n fd = self.f\n ens = self.ensemble\n k = ens.k\n cfg = self.cfg\n if self._source == 2:\n self.vars_read += ['latitude_gps', 'longitude_gps']\n fd.seek(2, 1)\n long1 = fd.read_ui16(1)\n fd.seek(6, 1)\n ens.latitude_gps[k] = fd.read_i32(1) * self._cfac\n if ens.latitude_gps[k] == 0:\n ens.latitude_gps[k] = np.NaN\n else:\n fd.seek(14, 1)\n ens.dist_bt[:, k] = fd.read_ui16(4) * 0.01\n ens.vel_bt[:, k] = fd.read_i16(4) * 0.001\n ens.corr_bt[:, k] = fd.read_ui8(4)\n ens.amp_bt[:, k] = fd.read_ui8(4)\n ens.prcnt_gd_bt[:, k] = fd.read_ui8(4)\n if self._source == 2:\n fd.seek(2, 1)\n ens.longitude_gps[k] = (\n long1 + 65536 * fd.read_ui16(1)) * self._cfac\n if ens.longitude_gps[k] > 180:\n ens.longitude_gps[k] = ens.longitude_gps[k] - 360\n if ens.longitude_gps[k] == 0:\n ens.longitude_gps[k] = np.NaN\n fd.seek(16, 1)\n qual = fd.read_ui8(1)\n if qual == 0:\n print(' qual==%d,%f %f' % (qual,\n ens.latitude_gps[k],\n ens.longitude_gps[k]))\n ens.latitude_gps[k] = np.NaN\n ens.longitude_gps[k] = np.NaN\n fd.seek(71 - 45 - 16 - 17, 1)\n self._nbyte = 2 + 68\n else:\n fd.seek(71 - 45, 1)\n self._nbyte = 2 + 68\n if cfg['prog_ver'] >= 5.3:\n fd.seek(78 - 71, 1)\n ens.dist_bt[:, k] = ens.dist_bt[:, k] + fd.read_ui8(4) * 655.36\n self._nbyte += 11\n if cfg['name'] == 'wh-adcp':\n if cfg['prog_ver'] >= 16.20:\n fd.seek(4, 1)\n self._nbyte += 4\n\n def read_vmdas(self,):\n \"\"\" Read something from VMDAS \"\"\"\n fd = self.f\n # The raw files produced by VMDAS contain a binary navigation data\n # block.\n self.cfg['sourceprog'] = 'VMDAS'\n ens = self.ensemble\n k = ens.k\n if self._source != 1 and self._debug_level >= 1:\n print(' \\n***** Apparently a VMDAS file \\n\\n')\n self._source = 1\n self.vars_read += ['time_gps',\n 'latitude_gps',\n 'longitude_gps',\n 'etime_gps',\n 'elatitude_gps',\n 'elongitude_gps',\n 'flags',\n 'ntime', ]\n utim = fd.read_ui8(4)\n date = tmlib.datetime(utim[2] + utim[3] * 256, utim[1], utim[0])\n # This byte is in hundredths of seconds (10s of milliseconds):\n time = tmlib.timedelta(milliseconds=(int(fd.read_ui32(1) / 10)))\n fd.seek(4, 1) # \"PC clock offset from UTC\" - clock drift in ms?\n ens.time_gps[k] = tmlib.date2epoch(date + time)[0]\n ens.latitude_gps[k] = fd.read_i32(1) * self._cfac\n ens.longitude_gps[k] = fd.read_i32(1) * self._cfac\n ens.etime_gps[k] = tmlib.date2epoch(date + tmlib.timedelta(\n milliseconds=int(fd.read_ui32(1) * 10)))[0]\n ens.elatitude_gps[k] = fd.read_i32(1) * self._cfac\n ens.elongitude_gps[k] = fd.read_i32(1) * self._cfac\n fd.seek(12, 1)\n ens.flags[k] = fd.read_ui16(1)\n fd.seek(6, 1)\n utim = fd.read_ui8(4)\n date = tmlib.datetime(utim[0] + utim[1] * 256, utim[3], utim[2])\n ens.ntime[k] = tmlib.date2epoch(date + tmlib.timedelta(\n milliseconds=int(fd.read_ui32(1) / 10)))[0]\n fd.seek(16, 1)\n self._nbyte = 2 + 76\n\n def read_winriver2(self, ):\n startpos = self.f.tell()\n self._winrivprob = True\n self.cfg['sourceprog'] = 'WINRIVER'\n ens = self.ensemble\n k = ens.k\n if self._source != 3 and self._debug_level >= 1:\n warnings.warn(' \\n***** Apparently a WINRIVER2 file\\n'\n '***** WARNING: Raw NMEA data '\n 'handler not yet fully implemented\\n\\n')\n self._source = 3\n spid = self.f.read_ui16(1)\n if spid == 104:\n sz = self.f.read_ui16(1)\n dtime = self.f.read_f64(1)\n start_string = self.f.reads(6)\n _ = self.f.reads(1)\n if start_string != '$GPGGA':\n if self._debug_level > 1:\n warnings.warn(f'Invalid GPGGA string found in ensemble {k},'\n ' skipping...')\n return 'FAIL'\n gga_time = str(self.f.reads(9))\n time = tmlib.timedelta(hours=int(gga_time[0:2]),\n minutes=int(gga_time[2:4]),\n seconds=int(gga_time[4:6]),\n milliseconds=int(gga_time[7:])*100)\n clock = self.ensemble.rtc[:, :]\n if clock[0, 0] < 100:\n clock[0, :] += century\n ens.time_gps[k] = tmlib.date2epoch(tmlib.datetime(\n *clock[:3, 0]) + time)[0]\n self.f.seek(1, 1)\n ens.latitude_gps[k] = self.f.read_f64(1)\n tcNS = self.f.reads(1)\n if tcNS == 'S':\n ens.latitude_gps[k] *= -1\n elif tcNS != 'N':\n if self._debug_level > 1:\n warnings.warn(f'Invalid GPGGA string found in ensemble {k},'\n ' skipping...')\n return 'FAIL'\n ens.longitude_gps[k] = self.f.read_f64(1)\n tcEW = self.f.reads(1)\n if tcEW == 'W':\n ens.longitude_gps[k] *= -1\n elif tcEW != 'E':\n if self._debug_level > 1:\n warnings.warn(f'Invalid GPGGA string found in ensemble {k},'\n ' skipping...')\n return 'FAIL'\n ucqual, n_sat = self.f.read_ui8(2)\n tmp = self.f.read_float(2)\n ens.hdop, ens.altitude = tmp\n if self.f.reads(1) != 'M':\n if self._debug_level > 1:\n warnings.warn(f'Invalid GPGGA string found in ensemble {k},'\n ' skipping...')\n return 'FAIL'\n ggeoid_sep = self.f.read_float(1)\n if self.f.reads(1) != 'M':\n if self._debug_level > 1:\n warnings.warn(f'Invalid GPGGA string found in ensemble {k},'\n ' skipping...')\n return 'FAIL'\n gage = self.f.read_float(1)\n gstation_id = self.f.read_ui16(1)\n # 4 unknown bytes (2 reserved+2 checksum?)\n # 78 bytes for GPGGA string (including \\r\\n)\n # 2 reserved + 2 checksum\n self.vars_read += ['longitude_gps', 'latitude_gps', 'time_gps']\n self._nbyte = self.f.tell() - startpos + 2\n if self._debug_level >= 5:\n print('')\n print(sz, ens.longitude_gps[k])\n\n def read_winriver(self, nbt):\n self._winrivprob = True\n self.cfg['sourceprog'] = 'WINRIVER'\n if self._source not in [2, 3]:\n if self._debug_level >= 1:\n warnings.warn('\\n ***** Apparently a WINRIVER file - '\n 'Raw NMEA data handler not yet implemented\\n\\n')\n self._source = 2\n startpos = self.f.tell()\n sz = self.f.read_ui16(1)\n tmp = self.f.reads(sz)\n self._nbyte = self.f.tell() - startpos + 2\n\n def skip_Ncol(self, n_skip=1):\n self.f.seek(n_skip * self.cfg['n_cells'], 1)\n self._nbyte = 2 + n_skip * self.cfg['n_cells']\n\n def skip_Nbyte(self, n_skip):\n self.f.seek(n_skip, 1)\n self._nbyte = self._nbyte = 2 + n_skip\n\n def read_nocode(self, id):\n # Skipping bytes from codes 0340-30FC, commented if needed\n # hxid = hex(id)\n # if hxid[2:4] == '30':\n # raise Exception(\"\")\n # # I want to count the number of 1s in the middle 4 bits\n # # of the 2nd two bytes.\n # # 60 is a 0b00111100 mask\n # nflds = (bin(int(hxid[3]) & 60).count('1') +\n # bin(int(hxid[4]) & 60).count('1'))\n # # I want to count the number of 1s in the highest\n # # 2 bits of byte 3\n # # 3 is a 0b00000011 mask:\n # dfac = bin(int(hxid[3], 0) & 3).count('1')\n # self.skip_Nbyte(12 * nflds * dfac)\n # else:\n print(' Unrecognized ID code: %0.4X\\n' % id)\n\n def remove_end(self, iens):\n dat = self.outd\n print(' Encountered end of file. Cleaning up data.')\n for nm in self.vars_read:\n _setd(dat, nm, _get(dat, nm)[..., :iens])\n\n def finalize(self, ):\n \"\"\"Remove the attributes from the data that were never loaded.\n \"\"\"\n dat = self.outd\n for nm in set(data_defs.keys()) - self.vars_read:\n _pop(dat, nm)\n for nm in self.cfg:\n dat['attrs'][nm] = self.cfg[nm]\n dat['attrs']['fs'] = (dat['attrs']['sec_between_ping_groups'] *\n dat['attrs']['pings_per_ensemble']) ** (-1)\n for nm in data_defs:\n shp = data_defs[nm][0]\n if len(shp) and shp[0] == 'nc' and _in_group(dat, nm):\n _setd(dat, nm, np.swapaxes(_get(dat, nm), 0, 1))\n\n def __exit__(self, type, value, traceback):\n self.f.close()\n\n def __enter__(self,):\n return self\n", "import dolfyn as dlfn\nimport dolfyn.adv.api as api\n\nimport numpy as np\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mpldt\n\n\n##############################################################################\n# User-input data\nfname = '../../dolfyn/example_data/vector_data_imu01.VEC'\naccel_filter = .03 # motion correction filter [Hz]\nensemble_size = 32*300 # sampling frequency * 300 seconds\n\n# Read the data in, use the '.userdata.json' file\ndata_raw = dlfn.read(fname, userdata=True)\n\n# Crop the data for the time range of interest:\nt_start = dlfn.time.date2dt64(datetime(2012, 6, 12, 12, 8, 30))\nt_end = data_raw.time[-1]\ndata = data_raw.sel(time=slice(t_start, t_end))\n\n\n##############################################################################\n# Clean the file using the Goring, Nikora 2002 method:\nbad = api.clean.GN2002(data.vel)\ndata['vel'] = api.clean.clean_fill(data.vel, bad, method='cubic')\n# To not replace data:\n# data.coords['mask'] = (('dir','time'), ~bad)\n# data.vel.values = data.vel.where(data.mask)\n\n# plotting raw vs qc'd data\nax = plt.figure(figsize=(20, 10)).add_axes([.14, .14, .8, .74])\nax.plot(data_raw.time, data_raw.velds.u, label='raw data')\nax.plot(data.time, data.velds.u, label='despiked')\nax.set_xlabel('Time')\nax.xaxis.set_major_formatter(mpldt.DateFormatter('%D %H:%M'))\nax.set_ylabel('u-dir velocity, (m/s)')\nax.set_title('Raw vs Despiked Data')\nplt.legend(loc='upper right')\nplt.show()\n\ndata_cleaned = data.copy(deep=True)\n\n\n##############################################################################\n# Perform motion correction\ndata = api.correct_motion(data, accel_filter, to_earth=False)\n# For reference, dolfyn defines ‘inst’ as the IMU frame of reference, not\n# the ADV sensor head\n# After motion correction, the pre- and post-correction datasets coordinates\n# may not align. Since here the ADV sensor head and battery body axes are\n# aligned, data.u is the same axis as data_cleaned.u\n\n# Plotting corrected vs uncorrect velocity in instrument coordinates\nax = plt.figure(figsize=(20, 10)).add_axes([.14, .14, .8, .74])\nax.plot(data_cleaned.time, data_cleaned.velds.u, 'g-', label='uncorrected')\nax.plot(data.time, data.velds.u, 'b-', label='motion-corrected')\nax.set_xlabel('Time')\nax.xaxis.set_major_formatter(mpldt.DateFormatter('%D %H:%M'))\nax.set_ylabel('u velocity, (m/s)')\nax.set_title('Pre- and Post- Motion Corrected Data in XYZ coordinates')\nplt.legend(loc='upper right')\nplt.show()\n\n\n# Rotate the uncorrected data into the earth frame for comparison to motion\n# correction:\ndlfn.rotate2(data, 'earth', inplace=True)\ndata_uncorrected = dlfn.rotate2(data_cleaned, 'earth', inplace=False)\n\n# Calc principal heading (from earth coordinates) and rotate into the\n# principal axes\ndata.attrs['principal_heading'] = dlfn.calc_principal_heading(data.vel)\ndata_uncorrected.attrs['principal_heading'] = dlfn.calc_principal_heading(\n data_uncorrected.vel)\n\n# Plotting corrected vs uncorrected velocity in principal coordinates\nax = plt.figure(figsize=(20, 10)).add_axes([.14, .14, .8, .74])\nax.plot(data_uncorrected.time, data_uncorrected.velds.u,\n 'g-', label='uncorrected')\nax.plot(data.time, data.velds.u, 'b-', label='motion-corrected')\nax.set_xlabel('Time')\nax.xaxis.set_major_formatter(mpldt.DateFormatter('%D %H:%M'))\nax.set_ylabel('streamwise velocity, (m/s)')\nax.set_title('Corrected and Uncorrected Data in Principal Coordinates')\nplt.legend(loc='upper right')\nplt.show()\n\n\n##############################################################################\n# Create velocity spectra\n# Initiate tool to bin data based on the ensemble length. If n_fft is none,\n# n_fft is equal to n_bin\nensemble_tool = api.ADVBinner(n_bin=9600, fs=data.fs, n_fft=4800)\n\n# motion corrected data\nmc_spec = ensemble_tool.calc_psd(data.vel, freq_units='Hz')\n# not-motion corrected data\nunm_spec = ensemble_tool.calc_psd(data_uncorrected.vel, freq_units='Hz')\n# Find motion spectra from IMU velocity\nuh_spec = ensemble_tool.calc_psd(data['velacc'] + data['velrot'],\n freq_units='Hz')\n\n# Plot U, V, W spectra\nU = ['u', 'v', 'w']\nfor i in range(len(U)):\n plt.figure(figsize=(15, 13))\n plt.loglog(uh_spec.f, uh_spec[i].mean(axis=0), 'c',\n label=('motion spectra ' + str(accel_filter) + 'Hz filter'))\n plt.loglog(unm_spec.f, unm_spec[i].mean(axis=0), 'r', label='uncorrected')\n plt.loglog(mc_spec.f, mc_spec[i].mean(\n axis=0), 'b', label='motion corrected')\n\n # plot -5/3 line\n f_tmp = np.logspace(-2, 1)\n plt.plot(f_tmp, 4e-5*f_tmp**(-5/3), 'k--', label='f^-5/3 slope')\n\n if U[i] == 'u':\n plt.title('Spectra in streamwise dir')\n elif U[i] == 'v':\n plt.title('Spectra in cross-stream dir')\n else:\n plt.title('Spectra in up dir')\n plt.xlabel('Freq [Hz]')\n plt.ylabel('$\\mathrm{[m^2s^{-2}/Hz]}$', size='large')\n plt.legend()\nplt.show()\n" ]
[ [ "numpy.unique", "numpy.isnan", "numpy.arange", "numpy.median", "numpy.nanmean", "numpy.array", "numpy.zeros", "numpy.empty" ], [ "matplotlib.pyplot.legend", "matplotlib.dates.DateFormatter", "matplotlib.pyplot.title", "numpy.logspace", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Prepaire/MolGNN_fewshot
[ "c7c17afdeae7f2ef0c8e3ca2da033091ec7537ca", "c7c17afdeae7f2ef0c8e3ca2da033091ec7537ca" ]
[ "chem/util.py", "chem/pretrain_fingerprint.py" ]
[ "import torch\nimport random\nimport collections\n\nimport networkx as nx\nfrom rdkit.Chem import AllChem\nimport numpy as np\n\nfrom loader import graph_data_obj_to_nx_simple, nx_to_graph_data_obj_simple\n\nfrom loader import MoleculeDataset\n\n\ndef get_filtered_fingerprint(smiles):\n \"\"\" Get filtered PubChem fingerprint. The digits related to elements other than C,\n H, O, N, S, F, Cl, and Br are discarded.\n\n Args:\n smiles (str): SMILES string.\n\n Return:\n fp (np.ndarray): The filtered PubChem fingerprint as a vector.\n length (int): length of the filtered vector.\n \"\"\"\n from PyFingerprint.All_Fingerprint import get_fingerprint\n\n fp = get_fingerprint(smiles, fp_type=\"pubchem\", output=\"vector\")\n del_pos = (\n [\n 26,\n 27,\n 28,\n 29,\n 30,\n 31,\n 32,\n 41,\n 42,\n 46,\n 47,\n 48,\n 295,\n 296,\n 298,\n 303,\n 304,\n 348,\n 354,\n 369,\n 407,\n 411,\n 415,\n 456,\n 525,\n 627,\n ]\n + list(range(49, 115))\n + list(range(263, 283))\n + list(range(288, 293))\n + list(range(310, 317))\n + list(range(318, 327))\n + list(range(327, 332))\n + list(range(424, 427))\n )\n fp = np.delete(fp, del_pos)\n return fp\n\n\ndef check_same_molecules(s1, s2):\n mol1 = AllChem.MolFromSmiles(s1)\n mol2 = AllChem.MolFromSmiles(s2)\n return AllChem.MolToInchi(mol1) == AllChem.MolToInchi(mol2)\n\n\nclass NegativeEdge:\n def __init__(self):\n \"\"\"\n Randomly sample negative edges\n \"\"\"\n pass\n\n def __call__(self, data):\n num_nodes = data.num_nodes\n num_edges = data.num_edges\n\n edge_set = set(\n [\n str(data.edge_index[0, i].cpu().item())\n + \",\"\n + str(data.edge_index[1, i].cpu().item())\n for i in range(data.edge_index.shape[1])\n ]\n )\n\n redandunt_sample = torch.randint(0, num_nodes, (2, 5 * num_edges))\n sampled_ind = []\n sampled_edge_set = set([])\n for i in range(5 * num_edges):\n node1 = redandunt_sample[0, i].cpu().item()\n node2 = redandunt_sample[1, i].cpu().item()\n edge_str = str(node1) + \",\" + str(node2)\n if not any(\n [edge_str in edge_set, edge_str in sampled_edge_set, node1 == node2]\n ):\n sampled_edge_set.add(edge_str)\n sampled_ind.append(i)\n if len(sampled_ind) == num_edges / 2:\n break\n\n data.negative_edge_index = redandunt_sample[:, sampled_ind]\n\n return data\n\n\nclass ExtractSubstructureContextPair:\n def __init__(self, k, l1, l2):\n \"\"\"\n Randomly selects a node from the data object, and adds attributes\n that contain the substructure that corresponds to k hop neighbours\n rooted at the node, and the context substructures that corresponds to\n the subgraph that is between l1 and l2 hops away from the\n root node.\n :param k:\n :param l1:\n :param l2:\n \"\"\"\n self.k = k\n self.l1 = l1\n self.l2 = l2\n\n # for the special case of 0, addresses the quirk with\n # single_source_shortest_path_length\n if self.k == 0:\n self.k = -1\n if self.l1 == 0:\n self.l1 = -1\n if self.l2 == 0:\n self.l2 = -1\n\n def __call__(self, data, root_idx=None):\n \"\"\"\n\n :param data: pytorch geometric data object\n :param root_idx: If None, then randomly samples an atom idx.\n Otherwise sets atom idx of root (for debugging only)\n :return: None. Creates new attributes in original data object:\n data.center_substruct_idx\n data.x_substruct\n data.edge_attr_substruct\n data.edge_index_substruct\n data.x_context\n data.edge_attr_context\n data.edge_index_context\n data.overlap_context_substruct_idx\n \"\"\"\n num_atoms = data.x.size(0)\n if root_idx is None:\n root_idx = random.sample(range(num_atoms), 1)[0]\n\n G = graph_data_obj_to_nx_simple(data) # same ordering as input data obj\n\n # Get k-hop subgraph rooted at specified atom idx\n substruct_node_idxes = nx.single_source_shortest_path_length(\n G, root_idx, self.k\n ).keys()\n if len(substruct_node_idxes) > 0:\n substruct_G = G.subgraph(substruct_node_idxes)\n substruct_G, substruct_node_map = reset_idxes(substruct_G) # need\n # to reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\n # make sense, since the node indices in data obj must start at 0\n substruct_data = nx_to_graph_data_obj_simple(substruct_G)\n data.x_substruct = substruct_data.x\n data.edge_attr_substruct = substruct_data.edge_attr\n data.edge_index_substruct = substruct_data.edge_index\n data.center_substruct_idx = torch.tensor(\n [substruct_node_map[root_idx]]\n ) # need\n # to convert center idx from original graph node ordering to the\n # new substruct node ordering\n\n # Get subgraphs that is between l1 and l2 hops away from the root node\n l1_node_idxes = nx.single_source_shortest_path_length(\n G, root_idx, self.l1\n ).keys()\n l2_node_idxes = nx.single_source_shortest_path_length(\n G, root_idx, self.l2\n ).keys()\n context_node_idxes = set(l1_node_idxes).symmetric_difference(set(l2_node_idxes))\n if len(context_node_idxes) > 0:\n context_G = G.subgraph(context_node_idxes)\n context_G, context_node_map = reset_idxes(context_G) # need to\n # reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\n # make sense, since the node indices in data obj must start at 0\n context_data = nx_to_graph_data_obj_simple(context_G)\n data.x_context = context_data.x\n data.edge_attr_context = context_data.edge_attr\n data.edge_index_context = context_data.edge_index\n\n # Get indices of overlapping nodes between substruct and context,\n # WRT context ordering\n context_substruct_overlap_idxes = list(\n set(context_node_idxes).intersection(set(substruct_node_idxes))\n )\n if len(context_substruct_overlap_idxes) > 0:\n context_substruct_overlap_idxes_reorder = [\n context_node_map[old_idx] for old_idx in context_substruct_overlap_idxes\n ]\n # need to convert the overlap node idxes, which is from the\n # original graph node ordering to the new context node ordering\n data.overlap_context_substruct_idx = torch.tensor(\n context_substruct_overlap_idxes_reorder\n )\n\n return data\n\n # ### For debugging ###\n # if len(substruct_node_idxes) > 0:\n # substruct_mol = graph_data_obj_to_mol_simple(data.x_substruct,\n # data.edge_index_substruct,\n # data.edge_attr_substruct)\n # print(AllChem.MolToSmiles(substruct_mol))\n # if len(context_node_idxes) > 0:\n # context_mol = graph_data_obj_to_mol_simple(data.x_context,\n # data.edge_index_context,\n # data.edge_attr_context)\n # print(AllChem.MolToSmiles(context_mol))\n #\n # print(list(context_node_idxes))\n # print(list(substruct_node_idxes))\n # print(context_substruct_overlap_idxes)\n # ### End debugging ###\n\n def __repr__(self):\n return \"{}(k={},l1={}, l2={})\".format(\n self.__class__.__name__, self.k, self.l1, self.l2\n )\n\n\ndef reset_idxes(G):\n \"\"\"\n Resets node indices such that they are numbered from 0 to num_nodes - 1\n :param G:\n :return: copy of G with relabelled node indices, mapping\n \"\"\"\n mapping = {}\n for new_idx, old_idx in enumerate(G.nodes()):\n mapping[old_idx] = new_idx\n new_G = nx.relabel_nodes(G, mapping, copy=True)\n return new_G, mapping\n\n\n# TODO(Bowen): more unittests\nclass MaskAtom:\n def __init__(self, num_atom_features, num_edge_type, mask_rate, mask_edge=True):\n \"\"\"\n Randomly masks an atom, and optionally masks edges connecting to it.\n The mask atom type index is num_possible_atom_type\n The mask edge type index in num_possible_edge_type\n :param num_atom_type:\n :param num_edge_type:\n :param mask_rate: % of atoms to be masked\n :param mask_edge: If True, also mask the edges that connect to the\n masked atoms\n \"\"\"\n self.num_atom_features = num_atom_features\n self.num_edge_type = num_edge_type\n self.mask_rate = mask_rate\n self.mask_edge = mask_edge\n\n def __call__(self, data, masked_atom_indices=None):\n \"\"\"\n\n :param data: pytorch geometric data object. Assume that the edge\n ordering is the default pytorch geometric ordering, where the two\n directions of a single edge occur in pairs.\n Eg. data.edge_index = tensor([[0, 1, 1, 2, 2, 3],\n [1, 0, 2, 1, 3, 2]])\n :param masked_atom_indices: If None, then randomly samples num_atoms\n * mask rate number of atom indices\n Otherwise a list of atom idx that sets the atoms to be masked (for\n debugging only)\n :return: None, Creates new attributes in original data object:\n data.mask_node_idx\n data.mask_node_label\n data.mask_edge_idx\n data.mask_edge_label\n \"\"\"\n\n if masked_atom_indices is None:\n # sample x distinct atoms to be masked, based on mask rate. But\n # will sample at least 1 atom\n num_atoms = data.x.size()[0]\n sample_size = int(round(num_atoms * self.mask_rate))\n if sample_size == 0:\n sample_size = 1\n masked_atom_indices = random.sample(range(num_atoms), sample_size)\n\n # create mask node label by copying atom feature of mask atom\n mask_node_labels_list = []\n for atom_idx in masked_atom_indices:\n mask_node_labels_list.append(data.x[atom_idx].view(1, -1))\n data.mask_node_label = torch.cat(mask_node_labels_list, dim=0)\n data.masked_atom_indices = torch.tensor(masked_atom_indices)\n\n # modify the original node feature of the masked node\n for atom_idx in masked_atom_indices:\n data.x[atom_idx] = torch.tensor([0] * self.num_atom_features)\n\n if self.mask_edge:\n # create mask edge labels by copying edge features of edges that are bonded\n # to mask atoms\n connected_edge_indices = []\n for bond_idx, (u, v) in enumerate(data.edge_index.cpu().numpy().T):\n for atom_idx in masked_atom_indices:\n if (\n atom_idx in set((u, v))\n and bond_idx not in connected_edge_indices\n ):\n connected_edge_indices.append(bond_idx)\n\n if len(connected_edge_indices) > 0:\n # create mask edge labels by copying bond features of the bonds\n # connected to the mask atoms\n mask_edge_labels_list = []\n for bond_idx in connected_edge_indices[::2]: # because the\n # edge ordering is such that two directions of a single\n # edge occur in pairs, so to get the unique undirected\n # edge indices, we take every 2nd edge index from list\n mask_edge_labels_list.append(data.edge_attr[bond_idx].view(1, -1))\n\n data.mask_edge_label = torch.cat(mask_edge_labels_list, dim=0)\n # modify the original bond features of the bonds connected to the mask\n # atoms\n for bond_idx in connected_edge_indices:\n data.edge_attr[bond_idx] = torch.tensor([self.num_edge_type, 0])\n\n data.connected_edge_indices = torch.tensor(connected_edge_indices[::2])\n else:\n data.mask_edge_label = torch.empty((0, 2)).to(torch.int64)\n data.connected_edge_indices = torch.tensor(connected_edge_indices).to(\n torch.int64\n )\n\n # data.x = data.x[2:]\n\n return data\n\n def __repr__(self):\n reprs = \"{}(num_atom_features={}, num_edge_type={}, mask_rate={}, mask_edge={})\"\n return reprs.format(\n self.__class__.__name__,\n self.num_atom_features,\n self.num_edge_type,\n self.mask_rate,\n self.mask_edge,\n )\n\n\nclass ONEHOT_ContextPair(object):\n\n ONEHOTENCODING_CODEBOOKS = {\n \"atom_type\": list(range(119)),\n \"degree\": list(range(11)),\n \"formal_charge\": list(range(11)),\n \"hybridization_type\": list(range(7)),\n \"aromatic\": [0, 1],\n \"chirality_type\": [0, 1, 2, 3],\n }\n\n def __init__(self, dataset, k, l1, l2):\n\n self.dataset = dataset\n self.k = k\n self.l1 = l1\n self.l2 = l2\n\n # for the special case of 0, addresses the quirk with\n # single_source_shortest_path_length\n if self.k == 0:\n self.k = -1\n if self.l1 == 0:\n self.l1 = -1\n if self.l2 == 0:\n self.l2 = -1\n\n self.FEATURE_NAMES = [\n \"atom_type\",\n \"degree\",\n \"formal_charge\",\n \"hybridization_type\",\n \"aromatic\",\n \"chirality_type\",\n ]\n self.ONEHOTENCODING = [0, 1, 2, 3, 4, 5]\n\n def get_CODEBOOKS(self):\n if self.ONEHOTENCODING_CODEBOOKS:\n # print(\"ONEHOTENCODING_CODEBOOKS is available already, do not need to\n # regenerate ONEHOTENCODING_CODEBOOKS\")\n # print(ONEHOTENCODING_CODEBOOKS)\n return\n\n # print(f\"generating ONEHOTENCODING_CODEBOOKS......\")\n features_all = [data.x.numpy() for data in self.dataset]\n features = np.vstack(features_all)\n node_attributes_cnt = {}\n for j, col in enumerate(zip(*features)):\n node_attributes_cnt[self.FEATURE_NAMES[j]] = collections.Counter(col)\n\n self.ONEHOTENCODING_CODEBOOKS.update(\n {\n feature_name: sorted(node_attributes_cnt[feature_name].keys())\n for feature_name in self.FEATURE_NAMES\n }\n )\n\n def get_onehot_features(self, features):\n feature_one_hot = []\n # print(f'input features{features}')\n for row in features.tolist():\n this_row = []\n for j, feature_val_before_onehot in enumerate(row):\n onehot_code = self.ONEHOTENCODING_CODEBOOKS[self.FEATURE_NAMES[j]]\n onehot_val = [0.0] * len(onehot_code)\n assert feature_val_before_onehot in onehot_code\n onehot_val[onehot_code.index(feature_val_before_onehot)] = 1.0\n this_row += onehot_val\n feature_one_hot.append(this_row)\n return torch.Tensor(feature_one_hot)\n\n def __call__(self, data, root_idx=None):\n\n self.get_CODEBOOKS()\n # print(f'before onehot data {data.x.numpy()}')\n\n num_atoms = data.x.size(0)\n if root_idx is None:\n root_idx = random.sample(range(num_atoms), 1)[0]\n\n G = graph_data_obj_to_nx_simple(data) # same ordering as input data obj\n\n # Get k-hop subgraph rooted at specified atom idx\n substruct_node_idxes = nx.single_source_shortest_path_length(\n G, root_idx, self.k\n ).keys()\n if len(substruct_node_idxes) > 0:\n substruct_G = G.subgraph(substruct_node_idxes)\n substruct_G, substruct_node_map = reset_idxes(substruct_G) # need\n # to reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\n # make sense, since the node indices in data obj must start at 0\n substruct_data = nx_to_graph_data_obj_simple(substruct_G)\n data.x_substruct = substruct_data.x\n data.edge_attr_substruct = substruct_data.edge_attr\n data.edge_index_substruct = substruct_data.edge_index\n data.center_substruct_idx = torch.tensor(\n [substruct_node_map[root_idx]]\n ) # need\n # to convert center idx from original graph node ordering to the\n # new substruct node ordering\n\n data.x_substruct = self.get_onehot_features(data.x_substruct.numpy())\n # Get subgraphs that is between l1 and l2 hops away from the root node\n l1_node_idxes = nx.single_source_shortest_path_length(\n G, root_idx, self.l1\n ).keys()\n l2_node_idxes = nx.single_source_shortest_path_length(\n G, root_idx, self.l2\n ).keys()\n context_node_idxes = set(l1_node_idxes).symmetric_difference(set(l2_node_idxes))\n if len(context_node_idxes) > 0:\n context_G = G.subgraph(context_node_idxes)\n context_G, context_node_map = reset_idxes(context_G) # need to\n # reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\n # make sense, since the node indices in data obj must start at 0\n context_data = nx_to_graph_data_obj_simple(context_G)\n data.x_context = context_data.x\n data.edge_attr_context = context_data.edge_attr\n data.edge_index_context = context_data.edge_index\n data.x_context = self.get_onehot_features(data.x_context.numpy())\n\n # Get indices of overlapping nodes between substruct and context,\n # WRT context ordering\n context_substruct_overlap_idxes = list(\n set(context_node_idxes).intersection(set(substruct_node_idxes))\n )\n if len(context_substruct_overlap_idxes) > 0:\n context_substruct_overlap_idxes_reorder = [\n context_node_map[old_idx] for old_idx in context_substruct_overlap_idxes\n ]\n # need to convert the overlap node idxes, which is from the\n # original graph node ordering to the new context node ordering\n data.overlap_context_substruct_idx = torch.tensor(\n context_substruct_overlap_idxes_reorder\n )\n\n # print(f'after onehot data{onehot_features.size()}')\n\n # print()\n # print ( data )\n return data\n\n def __repr__(self):\n return \"{}(k={},l1={}, l2={})\".format(\n self.__class__.__name__, self.k, self.l1, self.l2\n )\n\n # def __repr__(self):\n # return f'{self.__class__.__name__}'\n\n \n \n \n \n \n \nclass ONEHOT_ENCODING(object):\n \n \n ONEHOTENCODING_CODEBOOKS = {\n \"atom_type\": list(range(119)),\n \"degree\": list(range(11)),\n \"formal_charge\": list(range(11)),\n \"hybridization_type\": list(range(7)),\n \"aromatic\": [0, 1],\n \"chirality_type\": [0, 1, 2, 3],\n}\n\n\n\n def __init__(self, dataset):\n\n self.dataset = dataset \n\n \n self.FEATURE_NAMES = [\n \"atom_type\",\n \"degree\",\n \"formal_charge\",\n \"hybridization_type\",\n \"aromatic\",\n \"chirality_type\",\n ]\n self.ONEHOTENCODING = [0, 1, 2, 3, 4, 5]\n \n \n def get_CODEBOOKS(self):\n \n \n if self.ONEHOTENCODING_CODEBOOKS:\n # print(\"ONEHOTENCODING_CODEBOOKS is available already, do not need to\n # regenerate ONEHOTENCODING_CODEBOOKS\")\n # print(ONEHOTENCODING_CODEBOOKS)\n return\n\n \n features_all = [data.x.numpy() for data in self.dataset]\n features = np.vstack(features_all)\n node_attributes_cnt = {}\n for j, col in enumerate(zip(*features)):\n node_attributes_cnt[self.FEATURE_NAMES[j]] = collections.Counter(col)\n\n ONEHOTENCODING_CODEBOOKS.update({\n feature_name: sorted(node_attributes_cnt[feature_name].keys())\n for feature_name in self.FEATURE_NAMES} )\n \n #print(f\"generating ONEHOTENCODING_CODEBOOKS......\")\n\n \n def get_onehot_features(self,features):\n feature_one_hot = []\n #print(f'input features{features}')\n for row in features.tolist():\n this_row = []\n for j, feature_val_before_onehot in enumerate(row):\n onehot_code = self.ONEHOTENCODING_CODEBOOKS[self.FEATURE_NAMES[j]]\n onehot_val = [0.0] * len(onehot_code)\n assert feature_val_before_onehot in onehot_code\n onehot_val[onehot_code.index(feature_val_before_onehot)] = 1.0 \n this_row += onehot_val\n feature_one_hot.append(this_row)\n return torch.Tensor(feature_one_hot)\n\n\n def __call__(self, data):\n\n self.get_CODEBOOKS()\n #print(f'before onehot data {data.x.numpy()}')\n onehot_features = self.get_onehot_features(data.x.numpy()) \n #print(f'after onehot data{onehot_features.size()}')\n data.x = onehot_features\n #print()\n #print ( data )\n return data\n \n\n def __repr__(self):\n return f'{self.__class__.__name__}'\n\nif __name__ == \"__main__\":\n transform = NegativeEdge()\n dataset = MoleculeDataset(\"dataset/tox21\", dataset=\"tox21\")\n transform(dataset[0])\n\n \"\"\"\n # TODO(Bowen): more unit tests\n # test ExtractSubstructureContextPair\n\n smiles = 'C#Cc1c(O)c(Cl)cc(/C=C/N)c1S'\n m = AllChem.MolFromSmiles(smiles)\n data = mol_to_graph_data_obj_simple(m)\n root_idx = 13\n\n # 0 hops: no substructure or context. We just test the absence of x attr\n transform = ExtractSubstructureContextPair(0, 0, 0)\n transform(data, root_idx)\n assert not hasattr(data, 'x_substruct')\n assert not hasattr(data, 'x_context')\n\n # k > n_nodes, l1 = 0 and l2 > n_nodes: substructure and context same as\n # molecule\n data = mol_to_graph_data_obj_simple(m)\n transform = ExtractSubstructureContextPair(100000, 0, 100000)\n transform(data, root_idx)\n substruct_mol = graph_data_obj_to_mol_simple(data.x_substruct,\n data.edge_index_substruct,\n data.edge_attr_substruct)\n context_mol = graph_data_obj_to_mol_simple(data.x_context,\n data.edge_index_context,\n data.edge_attr_context)\n assert check_same_molecules(AllChem.MolToSmiles(substruct_mol),\n AllChem.MolToSmiles(context_mol))\n\n transform = ExtractSubstructureContextPair(1, 1, 10000)\n transform(data, root_idx)\n\n # increase k from 0, and increase l1 from 1 while keeping l2 > n_nodes: the\n # total number of atoms should be n_atoms\n for i in range(len(m.GetAtoms())):\n data = mol_to_graph_data_obj_simple(m)\n print('i: {}'.format(i))\n transform = ExtractSubstructureContextPair(i, i, 100000)\n transform(data, root_idx)\n if hasattr(data, 'x_substruct'):\n n_substruct_atoms = data.x_substruct.size()[0]\n else:\n n_substruct_atoms = 0\n print('n_substruct_atoms: {}'.format(n_substruct_atoms))\n if hasattr(data, 'x_context'):\n n_context_atoms = data.x_context.size()[0]\n else:\n n_context_atoms = 0\n print('n_context_atoms: {}'.format(n_context_atoms))\n assert n_substruct_atoms + n_context_atoms == len(m.GetAtoms())\n\n # l1 < k and l2 >= k, so an overlap exists between context and substruct\n data = mol_to_graph_data_obj_simple(m)\n transform = ExtractSubstructureContextPair(2, 1, 3)\n transform(data, root_idx)\n assert hasattr(data, 'center_substruct_idx')\n\n # check correct overlap atoms between context and substruct\n\n\n # m = AllChem.MolFromSmiles('COC1=CC2=C(NC(=N2)[S@@](=O)CC2=NC=C(C)C(OC)=C2C)C=C1')\n # data = mol_to_graph_data_obj_simple(m)\n # root_idx = 9\n # k = 1\n # l1 = 1\n # l2 = 2\n # transform = ExtractSubstructureContextPaidata =\n # mol_to_graph_data_obj_simple(m)r(k, l1, l2)\n # transform(data, root_idx)\n pass\n\n # TODO(Bowen): more unit tests\n # test MaskAtom\n from loader import mol_to_graph_data_obj_simple, \\\n graph_data_obj_to_mol_simple\n\n smiles = 'C#Cc1c(O)c(Cl)cc(/C=C/N)c1S'\n m = AllChem.MolFromSmiles(smiles)\n original_data = mol_to_graph_data_obj_simple(m)\n num_atom_type = 118\n num_edge_type = 5\n\n # manually specify masked atom indices, don't mask edge\n masked_atom_indices = [13, 12]\n data = mol_to_graph_data_obj_simple(m)\n transform = MaskAtom(num_atom_type, num_edge_type, 0.1, mask_edge=False)\n transform(data, masked_atom_indices)\n assert data.mask_node_label.size() == torch.Size(\n (len(masked_atom_indices), 2))\n assert not hasattr(data, 'mask_edge_label')\n # check that the correct rows in x have been modified to be mask atom type\n assert (data.x[masked_atom_indices] == torch.tensor(([num_atom_type,\n 0]))).all()\n assert (data.mask_node_label == original_data.x[masked_atom_indices]).all()\n\n # manually specify masked atom indices, mask edge\n masked_atom_indices = [13, 12]\n data = mol_to_graph_data_obj_simple(m)\n transform = MaskAtom(num_atom_type, num_edge_type, 0.1, mask_edge=True)\n transform(data, masked_atom_indices)\n assert data.mask_node_label.size() == torch.Size(\n (len(masked_atom_indices), 2))\n # check that the correct rows in x have been modified to be mask atom type\n assert (data.x[masked_atom_indices] == torch.tensor(([num_atom_type,\n 0]))).all()\n assert (data.mask_node_label == original_data.x[masked_atom_indices]).all()\n # check that the correct rows in edge_attr have been modified to be mask edge\n # type, and the mask_edge_label are correct\n rdkit_bonds = []\n for atom_idx in masked_atom_indices:\n bond_indices = list(AllChem.FindAtomEnvironmentOfRadiusN(m, radius=1,\n rootedAtAtom=atom_idx))\n for bond_idx in bond_indices:\n rdkit_bonds.append(\n (m.GetBonds()[bond_idx].GetBeginAtomIdx(), m.GetBonds()[\n bond_idx].GetEndAtomIdx()))\n rdkit_bonds.append(\n (m.GetBonds()[bond_idx].GetEndAtomIdx(), m.GetBonds()[\n bond_idx].GetBeginAtomIdx()))\n rdkit_bonds = set(rdkit_bonds)\n connected_edge_indices = []\n for i in range(data.edge_index.size()[1]):\n if tuple(data.edge_index.numpy().T[i].tolist()) in rdkit_bonds:\n connected_edge_indices.append(i)\n assert (data.edge_attr[connected_edge_indices] ==\n torch.tensor(([num_edge_type, 0]))).all()\n assert (data.mask_edge_label == original_data.edge_attr[\n connected_edge_indices[::2]]).all() # data.mask_edge_label contains\n # the unique edges (ignoring direction). The data obj has edge ordering\n # such that two directions of a single edge occur in pairs, so to get the\n # unique undirected edge indices, we take every 2nd edge index from list\n \"\"\"\n", "import argparse\n\nfrom loader import MoleculeDataset\nfrom torch_geometric.data import DataLoader\nfrom Chembl_loader import ChemBLFP \nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch.optim as optim\n\n\nfrom tqdm import tqdm\nimport numpy as np\n\n\nfrom model import GNN, GNN_fingerprint\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom util import ONEHOT_ENCODING\n\n\ndef train( args, model, device, loader, optimizer, criterion):\n\n model.train()\n\n for step, batch in enumerate(tqdm(loader,desc='Iteration')):\n batch = batch.to(device)\n\n pred = model (batch.x, batch.edge_index, batch.edge_attr, batch.batch)\n\n y = batch.y\n y = y.float()\n pred = pred.float()\n assert (pred.size() == y.size())\n \n loss = criterion(pred, y) \n\n # backprop\n optimizer.zero_grad()\n #loss.backward()\n #loss.sum().backward()\n loss.sum().backward()\n optimizer.step()\n\n\ndef eval (args, model,device, loader,criterion):\n\n model.eval()\n y_true = []\n y_scores = []\n for step, batch in enumerate(tqdm(loader, desc=\"Iteration\")):\n batch = batch.to(device)\n\n with torch.no_grad():\n pred = model(batch.x, batch.edge_index, batch.edge_attr, batch.batch)\n # pred = model (batch.x, batch.edge_index, batch.batch) \n y_true.append(batch.y.cpu())\n y_scores.append(pred.cpu())\n y = batch.y\n y = y.float()\n pred = pred.float()\n loss = criterion(pred, y) \n\n\n y_true = torch.cat(y_true, dim=0).cpu().numpy()\n y_scores = torch.cat(y_scores, dim=0).cpu().numpy()\n roc_list = []\n\n for i in range(y_true.shape[1]):\n # AUC is only defined when there is at least one positive and one negative data.\n if np.sum(y_true[:, i] == 1) > 0 and np.sum(y_true[:, i] == 0) > 0:\n\n roc_list.append(\n roc_auc_score(y_true[:, i], y_scores[:, i])\n )\n\n \n\n\n\n return roc_list\n\n \ndef main():\n # Training settings\n \n \n parser = argparse.ArgumentParser(description='PyTorch implementation of pre-training of fingerprint')\n\n parser.add_argument('--device', type=int, default=0,\n help='which gpu to use if any (default: 0)')\n parser.add_argument('--batch_size', type=int, default=32,\n help='input batch size for training (default: 32)')\n parser.add_argument('--epochs', type=int, default=100,\n help='number of epochs to train (default: 100)')\n parser.add_argument('--lr', type=float, default=0.001,\n help='learning rate (default: 0.001)')\n parser.add_argument('--decay', type=float, default=0,\n help='weight decay (default: 0)')\n parser.add_argument('--num_layer', type=int, default=5,\n help='number of GNN message passing layers (default: 5).')\n parser.add_argument('--emb_dim', type=int, default=256,\n help='embedding dimensions (default: 300)')\n \n parser.add_argument(\n \"--node_feat_dim\", type=int, default=154, help=\"dimension of the node features.\",\n )\n parser.add_argument(\n \"--edge_feat_dim\", type=int, default=2, help=\"dimension ofo the edge features.\"\n )\n\n\n parser.add_argument('--fingerprint_dim', type=int, default=740,\n help='embedding dimensions of FP(default:740)')\n parser.add_argument('--graph_pooling', type=str, default=\"mean\",\n help='graph level pooling (sum, mean, max, set2set, attention)')\n parser.add_argument('--dropout_ratio', type=float, default=0.2,\n help='dropout ratio (default: 0.2)')\n parser.add_argument('--JK', type=str, default=\"last\",\n help='how the node features across layers are combined. last, sum, max or concat')\n \n parser.add_argument('--dataset', type=str, default = 'chembl', help='root directory of dataset. For now, only fiingerprint.')\n parser.add_argument('--gnn_type', type=str, default=\"gine\")\n parser.add_argument('--input_model_file', type=str, default = 'chemblFiltered_pretrained_model_with_contextPred', help='filename to read the model (if there is any)')\n parser.add_argument('--output_model_file', type = str, default = 'trained_model/pre_FP_chembl', help='filename to output the pre-trained model')\n parser.add_argument('--num_workers', type=int, default = 4, help='number of workers for dataset loading')\n args = parser.parse_args()\n \n print(\"show all arguments configuration...\")\n print(args)\n\n\n torch.manual_seed(0)\n np.random.seed(0)\n device = torch.device(\"cuda:\" + str(args.device)) if torch.cuda.is_available() else torch.device(\"cpu\")\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(0)\n \n dataset_og = ChemBLFP(root=args.dataset)\n dataset = ChemBLFP(root=args.dataset , transform = ONEHOT_ENCODING(dataset = dataset_og))\n\n loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, num_workers = args.num_workers)\n #model = GNN_fingerprint(5, 300,fingerprint_dim=740, JK = 'last', graph_pooling = \"mean\" , drop_ratio = 0.2, gnn_type = 'gin') \n model = GNN_fingerprint (args.num_layer, args.node_feat_dim, args.edge_feat_dim,args.emb_dim, args.fingerprint_dim, args.JK, args.graph_pooling, args.dropout_ratio, args.gnn_type)\n\n if not args.input_model_file == \"\":\n model.from_pretrained(args.input_model_file + \".pth\")\n\n\n model.to(device)\n# print(f'model architecture:{model}')\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.decay) \n\n\n for epoch in range(1,args.epochs+1):\n print(\"====epoch \" + str(epoch))\n\n train(args, model, device, loader, optimizer,criterion=nn.BCEWithLogitsLoss(reduction = \"none\"))\n\n if not args.output_model_file == \"\":\n torch.save(model.gnn.state_dict(), args.output_model_file + \".pth\") \n\nif __name__ == \"__main__\":\n main()\n\n\n\n" ]
[ [ "torch.randint", "torch.empty", "torch.Tensor", "torch.cat", "torch.tensor", "numpy.delete", "numpy.vstack" ], [ "sklearn.metrics.roc_auc_score", "numpy.random.seed", "torch.cat", "torch.manual_seed", "torch.nn.BCEWithLogitsLoss", "torch.no_grad", "torch.cuda.is_available", "torch.cuda.manual_seed_all", "torch.device", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
eunice-chan/train-procgen
[ "3f7cc3e54c535ed41aa9cb510f408e87d74c87aa" ]
[ "train_procgen/evaluate.py" ]
[ "import tensorflow as tf\nfrom baselines.ppo2 import ppo2\nfrom baselines.common.models import build_impala_cnn\nfrom baselines.common.mpi_util import setup_mpi_gpus\nfrom procgen import ProcgenEnv\nfrom baselines.common.vec_env import (\n VecExtractDictObs,\n VecMonitor,\n VecFrameStack,\n VecNormalize\n)\nfrom baselines import logger\nfrom mpi4py import MPI\nimport argparse\nfrom .alternate_ppo2 import alt_ppo2\nimport os\nfrom baselines.common import set_global_seeds\nfrom baselines.common.policies import build_policy\n\ndef eval_fn(load_path, args, env_name='fruitbot', distribution_mode='easy', num_levels=500, start_level=500, log_dir='./tmp/procgen', comm=None, num_trials=3, gui=False):\n\n learning_rate = 5e-4\n ent_coef = .01\n gamma = .999\n lam = .95\n nsteps = 256\n nminibatches = 8\n ppo_epochs = 3\n clip_range = .2\n use_vf_clipping = True\n vf_coef = 0.5\n max_grad_norm = 0.5\n\n mpi_rank_weight = 1\n log_interval = 1\n seed=None\n\n log_comm = comm.Split(0, 0)\n format_strs = ['csv', 'stdout'] if log_comm.Get_rank() == 0 else []\n logger.configure(comm=log_comm, dir=log_dir, format_strs=format_strs)\n\n logger.info(\"creating environment\")\n venv = ProcgenEnv(num_envs=1, env_name=env_name, num_levels=num_levels, start_level=start_level, distribution_mode=distribution_mode)\n venv = VecExtractDictObs(venv, \"rgb\")\n\n venv = VecMonitor(\n venv=venv, filename=None, keep_buf=100,\n )\n\n venv = VecNormalize(venv=venv, ob=False)\n\n logger.info(\"creating tf session\")\n setup_mpi_gpus()\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True #pylint: disable=E1101\n sess = tf.Session(config=config)\n sess.__enter__()\n\n conv_fn = lambda x: build_impala_cnn(x, depths=[16,32,32], emb_size=256)\n\n logger.info(f\"evaluating\")\n\n set_global_seeds(seed)\n\n policy = build_policy(venv, conv_fn)\n\n # Get the nb of env\n nenvs = venv.num_envs\n # Get state_space and action_space\n ob_space = venv.observation_space\n ac_space = venv.action_space\n\n # Calculate the batch_size\n nbatch = nenvs * nsteps\n nbatch_train = nbatch // nminibatches\n\n # Instantiate the model object (that creates act_model and train_model)\n from .alternate_ppo2.model import Model\n model_fn = Model\n\n model = model_fn(policy=policy, ob_space=ob_space, ac_space=ac_space, nbatch_act=nenvs, nbatch_train=nbatch_train,\n nsteps=nsteps, ent_coef=ent_coef, vf_coef=vf_coef,\n max_grad_norm=max_grad_norm, comm=comm, mpi_rank_weight=mpi_rank_weight)\n\n if os.path.isfile(load_path):\n alt_ppo2.eval(\n network=conv_fn,\n nsteps=nsteps,\n ent_coef=ent_coef,\n vf_coef=vf_coef,\n max_grad_norm=max_grad_norm,\n gamma=gamma,\n lam=lam,\n log_interval=log_interval,\n nminibatches=nminibatches,\n noptepochs=ppo_epochs,\n load_path=load_path,\n mpi_rank_weight=mpi_rank_weight,\n comm=comm,\n clip_vf=use_vf_clipping,\n lr=learning_rate,\n cliprange=clip_range,\n policy=policy,\n nenvs=nenvs,\n ob_space=ob_space,\n ac_space=ac_space,\n nbatch=nbatch,\n nbatch_train=nbatch_train,\n model_fn=model_fn,\n model=model,\n num_trials=num_trials,\n num_levels=num_levels,\n start_level=start_level,\n gui=gui,\n args=args\n )\n elif os.path.isdir(load_path):\n for file in os.listdir(load_path):\n log_comm = comm.Split(0, 0)\n format_strs = ['csv', 'stdout'] if log_comm.Get_rank() == 0 else []\n logger.configure(comm=log_comm, dir=log_dir+'/'+file, format_strs=format_strs)\n alt_ppo2.eval(\n network=conv_fn,\n nsteps=nsteps,\n ent_coef=ent_coef,\n vf_coef=vf_coef,\n max_grad_norm=max_grad_norm,\n gamma=gamma,\n lam=lam,\n log_interval=log_interval,\n nminibatches=nminibatches,\n noptepochs=ppo_epochs,\n load_path=load_path+'/'+file,\n mpi_rank_weight=mpi_rank_weight,\n comm=comm,\n clip_vf=use_vf_clipping,\n lr=learning_rate,\n cliprange=clip_range,\n policy=policy,\n nenvs=nenvs,\n ob_space=ob_space,\n ac_space=ac_space,\n nbatch=nbatch,\n nbatch_train=nbatch_train,\n model_fn=model_fn,\n model=model,\n num_trials=num_trials,\n num_levels=num_levels,\n start_level=start_level,\n gui=gui,\n args=args\n )\n else:\n print('Model path does not exist.')\n return\n\ndef main():\n parser = argparse.ArgumentParser(description='Process procgen evaluation arguments.')\n parser.add_argument('--load_model', type=str, required=True)\n parser.add_argument('--log_dir', type=str, default='./logs/eval')\n parser.add_argument('--env_name', type=str, default='fruitbot')\n parser.add_argument('--distribution_mode', type=str, default='easy', choices=[\"easy\", \"hard\", \"exploration\", \"memory\", \"extreme\"])\n parser.add_argument('--num_levels', type=int, default=500)\n parser.add_argument('--start_level', type=int, default=0)\n parser.add_argument('--num_trials', type=int, default=3)\n parser.add_argument('--gui', action='store_true')\n\n args = parser.parse_args()\n\n comm = MPI.COMM_WORLD\n\n eval_fn(args.load_model,\n log_dir=args.log_dir,\n env_name=args.env_name,\n distribution_mode=args.distribution_mode,\n num_levels=args.num_levels,\n start_level=args.start_level,\n num_trials=args.num_trials,\n comm=comm,\n gui=args.gui,\n args=args\n )\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.ConfigProto", "tensorflow.Session" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
thomasjpfan/pyamg
[ "b0904d31c8da0c29affcd7d0fcd2bb8cb910b42a", "cabbb008fa26d4c9d8c24decf06374185864c88b" ]
[ "pyamg/aggregation/aggregation.py", "pyamg/vis/vtk_writer.py" ]
[ "\"\"\"Support for aggregation-based AMG.\"\"\"\nfrom __future__ import absolute_import\n\n\nfrom warnings import warn\nimport numpy as np\nfrom scipy.sparse import csr_matrix, isspmatrix_csr, isspmatrix_bsr,\\\n SparseEfficiencyWarning\n\nfrom pyamg.multilevel import multilevel_solver\nfrom pyamg.relaxation.smoothing import change_smoothers\nfrom pyamg.util.utils import relaxation_as_linear_operator,\\\n eliminate_diag_dom_nodes, blocksize,\\\n levelize_strength_or_aggregation, levelize_smooth_or_improve_candidates\nfrom pyamg.strength import classical_strength_of_connection,\\\n symmetric_strength_of_connection, evolution_strength_of_connection,\\\n energy_based_strength_of_connection, distance_strength_of_connection,\\\n algebraic_distance, affinity_distance\nfrom .aggregate import standard_aggregation, naive_aggregation,\\\n lloyd_aggregation\nfrom .tentative import fit_candidates\nfrom .smooth import jacobi_prolongation_smoother,\\\n richardson_prolongation_smoother, energy_prolongation_smoother\n\n__all__ = ['smoothed_aggregation_solver']\n\n\ndef smoothed_aggregation_solver(A, B=None, BH=None,\n symmetry='hermitian', strength='symmetric',\n aggregate='standard',\n smooth=('jacobi', {'omega': 4.0/3.0}),\n presmoother=('block_gauss_seidel',\n {'sweep': 'symmetric'}),\n postsmoother=('block_gauss_seidel',\n {'sweep': 'symmetric'}),\n improve_candidates=[('block_gauss_seidel',\n {'sweep': 'symmetric',\n 'iterations': 4}),\n None],\n max_levels=10, max_coarse=10,\n diagonal_dominance=False,\n keep=False, **kwargs):\n \"\"\"Create a multilevel solver using classical-style Smoothed Aggregation (SA).\n\n Parameters\n ----------\n A : csr_matrix, bsr_matrix\n Sparse NxN matrix in CSR or BSR format\n\n B : None, array_like\n Right near-nullspace candidates stored in the columns of an NxK array.\n The default value B=None is equivalent to B=ones((N,1))\n\n BH : None, array_like\n Left near-nullspace candidates stored in the columns of an NxK array.\n BH is only used if symmetry='nonsymmetric'.\n The default value B=None is equivalent to BH=B.copy()\n\n symmetry : string\n 'symmetric' refers to both real and complex symmetric\n 'hermitian' refers to both complex Hermitian and real Hermitian\n 'nonsymmetric' i.e. nonsymmetric in a hermitian sense\n Note, in the strictly real case, symmetric and hermitian are the same.\n Note, this flag does not denote definiteness of the operator.\n\n strength : string or list\n Method used to determine the strength of connection between unknowns of\n the linear system. Method-specific parameters may be passed in using a\n tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None,\n all nonzero entries of the matrix are considered strong.\n Choose from 'symmetric', 'classical', 'evolution', 'algebraic_distance',\n 'affinity', ('predefined', {'C' : csr_matrix}), None\n\n aggregate : string or list\n Method used to aggregate nodes.\n Choose from 'standard', 'lloyd', 'naive',\n ('predefined', {'AggOp' : csr_matrix})\n\n smooth : list\n Method used to smooth the tentative prolongator. Method-specific\n parameters may be passed in using a tuple, e.g. smooth=\n ('jacobi',{'filter' : True }).\n Choose from 'jacobi', 'richardson', 'energy', None\n\n presmoother : tuple, string, list\n Defines the presmoother for the multilevel cycling. The default block\n Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix\n is CSR or is a BSR matrix with blocksize of 1.\n\n postsmoother : tuple, string, list\n Same as presmoother, except defines the postsmoother.\n\n improve_candidates : tuple, string, list\n The ith entry defines the method used to improve the candidates B on\n level i. If the list is shorter than max_levels, then the last entry\n will define the method for all levels lower. If tuple or string, then\n this single relaxation descriptor defines improve_candidates on all\n levels.\n The list elements are relaxation descriptors of the form used for\n presmoother and postsmoother. A value of None implies no action on B.\n\n max_levels : integer\n Maximum number of levels to be used in the multilevel solver.\n\n max_coarse : integer\n Maximum number of variables permitted on the coarse grid.\n\n diagonal_dominance : bool, tuple\n If True (or the first tuple entry is True), then avoid coarsening\n diagonally dominant rows. The second tuple entry requires a\n dictionary, where the key value 'theta' is used to tune the diagonal\n dominance threshold.\n\n keep : bool\n Flag to indicate keeping extra operators in the hierarchy for\n diagnostics. For example, if True, then strength of connection (C),\n tentative prolongation (T), and aggregation (AggOp) are kept.\n\n Other Parameters\n ----------------\n cycle_type : ['V','W','F']\n Structrure of multigrid cycle\n\n coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ]\n Solver used at the coarsest level of the MG hierarchy.\n Optionally, may be a tuple (fn, args), where fn is a string such as\n ['splu', 'lu', ...] or a callable function, and args is a dictionary of\n arguments to be passed to fn.\n\n Returns\n -------\n ml : multilevel_solver\n Multigrid hierarchy of matrices and prolongation operators\n\n See Also\n --------\n multilevel_solver, classical.ruge_stuben_solver,\n aggregation.smoothed_aggregation_solver\n\n Notes\n -----\n - This method implements classical-style SA, not root-node style SA\n (see aggregation.rootnode_solver).\n\n - The additional parameters are passed through as arguments to\n multilevel_solver. Refer to pyamg.multilevel_solver for additional\n documentation.\n\n - At each level, four steps are executed in order to define the coarser\n level operator.\n\n 1. Matrix A is given and used to derive a strength matrix, C.\n\n 2. Based on the strength matrix, indices are grouped or aggregated.\n\n 3. The aggregates define coarse nodes and a tentative prolongation\n operator T is defined by injection\n\n 4. The tentative prolongation operator is smoothed by a relaxation\n scheme to improve the quality and extent of interpolation from the\n aggregates to fine nodes.\n\n - The parameters smooth, strength, aggregate, presmoother, postsmoother\n can be varied on a per level basis. For different methods on\n different levels, use a list as input so that the i-th entry defines\n the method at the i-th level. If there are more levels in the\n hierarchy than list entries, the last entry will define the method\n for all levels lower.\n\n Examples are:\n smooth=[('jacobi', {'omega':1.0}), None, 'jacobi']\n presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor']\n aggregate=['standard', 'naive']\n strength=[('symmetric', {'theta':0.25}), ('symmetric', {'theta':0.08})]\n\n - Predefined strength of connection and aggregation schemes can be\n specified. These options are best used together, but aggregation can\n be predefined while strength of connection is not.\n\n For predefined strength of connection, use a list consisting of\n tuples of the form ('predefined', {'C' : C0}), where C0 is a\n csr_matrix and each degree-of-freedom in C0 represents a supernode.\n For instance to predefine a three-level hierarchy, use\n [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ].\n\n Similarly for predefined aggregation, use a list of tuples. For\n instance to predefine a three-level hierarchy, use [('predefined',\n {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the\n dimensions of A, Agg0 and Agg1 are compatible, i.e. Agg0.shape[1] ==\n A.shape[0] and Agg1.shape[1] == Agg0.shape[0]. Each AggOp is a\n csr_matrix.\n\n Examples\n --------\n >>> from pyamg import smoothed_aggregation_solver\n >>> from pyamg.gallery import poisson\n >>> from scipy.sparse.linalg import cg\n >>> import numpy as np\n >>> A = poisson((100,100), format='csr') # matrix\n >>> b = np.ones((A.shape[0])) # RHS\n >>> ml = smoothed_aggregation_solver(A) # AMG solver\n >>> M = ml.aspreconditioner(cycle='V') # preconditioner\n >>> x,info = cg(A, b, tol=1e-8, maxiter=30, M=M) # solve with CG\n\n References\n ----------\n .. [1996VaMaBr] Vanek, P. and Mandel, J. and Brezina, M.,\n \"Algebraic Multigrid by Smoothed Aggregation for\n Second and Fourth Order Elliptic Problems\",\n Computing, vol. 56, no. 3, pp. 179--196, 1996.\n http://citeseer.ist.psu.edu/vanek96algebraic.html\n\n \"\"\"\n if not (isspmatrix_csr(A) or isspmatrix_bsr(A)):\n try:\n A = csr_matrix(A)\n warn(\"Implicit conversion of A to CSR\", SparseEfficiencyWarning)\n except BaseException:\n raise TypeError('Argument A must have type csr_matrix or bsr_matrix, or be convertible to csr_matrix')\n\n A = A.asfptype()\n\n if (symmetry != 'symmetric') and (symmetry != 'hermitian') and\\\n (symmetry != 'nonsymmetric'):\n raise ValueError('expected \\'symmetric\\', \\'nonsymmetric\\' or \\'hermitian\\' for the symmetry parameter ')\n A.symmetry = symmetry\n\n if A.shape[0] != A.shape[1]:\n raise ValueError('expected square matrix')\n\n # Right near nullspace candidates use constant for each variable as default\n if B is None:\n B = np.kron(np.ones((int(A.shape[0]/blocksize(A)), 1), dtype=A.dtype),\n np.eye(blocksize(A), dtype=A.dtype))\n else:\n B = np.asarray(B, dtype=A.dtype)\n if len(B.shape) == 1:\n B = B.reshape(-1, 1)\n if B.shape[0] != A.shape[0]:\n raise ValueError('The near null-space modes B have incorrect dimensions for matrix A')\n if B.shape[1] < blocksize(A):\n warn('Having less target vectors, B.shape[1], than blocksize of A can degrade convergence factors.')\n\n # Left near nullspace candidates\n if A.symmetry == 'nonsymmetric':\n if BH is None:\n BH = B.copy()\n else:\n BH = np.asarray(BH, dtype=A.dtype)\n if len(BH.shape) == 1:\n BH = BH.reshape(-1, 1)\n if BH.shape[1] != B.shape[1]:\n raise ValueError('The number of left and right near null-space modes B and BH, must be equal')\n if BH.shape[0] != A.shape[0]:\n raise ValueError('The near null-space modes BH have incorrect dimensions for matrix A')\n\n # Levelize the user parameters, so that they become lists describing the\n # desired user option on each level.\n max_levels, max_coarse, strength =\\\n levelize_strength_or_aggregation(strength, max_levels, max_coarse)\n max_levels, max_coarse, aggregate =\\\n levelize_strength_or_aggregation(aggregate, max_levels, max_coarse)\n improve_candidates =\\\n levelize_smooth_or_improve_candidates(improve_candidates, max_levels)\n smooth = levelize_smooth_or_improve_candidates(smooth, max_levels)\n\n # Construct multilevel structure\n levels = []\n levels.append(multilevel_solver.level())\n levels[-1].A = A # matrix\n\n # Append near nullspace candidates\n levels[-1].B = B # right candidates\n if A.symmetry == 'nonsymmetric':\n levels[-1].BH = BH # left candidates\n\n while len(levels) < max_levels and\\\n int(levels[-1].A.shape[0]/blocksize(levels[-1].A)) > max_coarse:\n extend_hierarchy(levels, strength, aggregate, smooth,\n improve_candidates, diagonal_dominance, keep)\n\n ml = multilevel_solver(levels, **kwargs)\n change_smoothers(ml, presmoother, postsmoother)\n return ml\n\n\ndef extend_hierarchy(levels, strength, aggregate, smooth, improve_candidates,\n diagonal_dominance=False, keep=True):\n \"\"\"Extend the multigrid hierarchy.\n\n Service routine to implement the strength of connection, aggregation,\n tentative prolongation construction, and prolongation smoothing. Called by\n smoothed_aggregation_solver.\n\n \"\"\"\n def unpack_arg(v):\n if isinstance(v, tuple):\n return v[0], v[1]\n else:\n return v, {}\n\n A = levels[-1].A\n B = levels[-1].B\n if A.symmetry == \"nonsymmetric\":\n AH = A.H.asformat(A.format)\n BH = levels[-1].BH\n\n # Compute the strength-of-connection matrix C, where larger\n # C[i,j] denote stronger couplings between i and j.\n fn, kwargs = unpack_arg(strength[len(levels)-1])\n if fn == 'symmetric':\n C = symmetric_strength_of_connection(A, **kwargs)\n elif fn == 'classical':\n C = classical_strength_of_connection(A, **kwargs)\n elif fn == 'distance':\n C = distance_strength_of_connection(A, **kwargs)\n elif (fn == 'ode') or (fn == 'evolution'):\n if 'B' in kwargs:\n C = evolution_strength_of_connection(A, **kwargs)\n else:\n C = evolution_strength_of_connection(A, B, **kwargs)\n elif fn == 'energy_based':\n C = energy_based_strength_of_connection(A, **kwargs)\n elif fn == 'predefined':\n C = kwargs['C'].tocsr()\n elif fn == 'algebraic_distance':\n C = algebraic_distance(A, **kwargs)\n elif fn == 'affinity':\n C = affinity_distance(A, **kwargs)\n elif fn is None:\n C = A.tocsr()\n else:\n raise ValueError('unrecognized strength of connection method: %s' %\n str(fn))\n\n # Avoid coarsening diagonally dominant rows\n flag, kwargs = unpack_arg(diagonal_dominance)\n if flag:\n C = eliminate_diag_dom_nodes(A, C, **kwargs)\n\n # Compute the aggregation matrix AggOp (i.e., the nodal coarsening of A).\n # AggOp is a boolean matrix, where the sparsity pattern for the k-th column\n # denotes the fine-grid nodes agglomerated into k-th coarse-grid node.\n fn, kwargs = unpack_arg(aggregate[len(levels)-1])\n if fn == 'standard':\n AggOp = standard_aggregation(C, **kwargs)[0]\n elif fn == 'naive':\n AggOp = naive_aggregation(C, **kwargs)[0]\n elif fn == 'lloyd':\n AggOp = lloyd_aggregation(C, **kwargs)[0]\n elif fn == 'predefined':\n AggOp = kwargs['AggOp'].tocsr()\n else:\n raise ValueError('unrecognized aggregation method %s' % str(fn))\n\n # Improve near nullspace candidates by relaxing on A B = 0\n fn, kwargs = unpack_arg(improve_candidates[len(levels)-1])\n if fn is not None:\n b = np.zeros((A.shape[0], 1), dtype=A.dtype)\n B = relaxation_as_linear_operator((fn, kwargs), A, b) * B\n levels[-1].B = B\n if A.symmetry == \"nonsymmetric\":\n BH = relaxation_as_linear_operator((fn, kwargs), AH, b) * BH\n levels[-1].BH = BH\n\n # Compute the tentative prolongator, T, which is a tentative interpolation\n # matrix from the coarse-grid to the fine-grid. T exactly interpolates\n # B_fine = T B_coarse.\n T, B = fit_candidates(AggOp, B)\n if A.symmetry == \"nonsymmetric\":\n TH, BH = fit_candidates(AggOp, BH)\n\n # Smooth the tentative prolongator, so that it's accuracy is greatly\n # improved for algebraically smooth error.\n fn, kwargs = unpack_arg(smooth[len(levels)-1])\n if fn == 'jacobi':\n P = jacobi_prolongation_smoother(A, T, C, B, **kwargs)\n elif fn == 'richardson':\n P = richardson_prolongation_smoother(A, T, **kwargs)\n elif fn == 'energy':\n P = energy_prolongation_smoother(A, T, C, B, None, (False, {}),\n **kwargs)\n elif fn is None:\n P = T\n else:\n raise ValueError('unrecognized prolongation smoother method %s' %\n str(fn))\n\n # Compute the restriction matrix, R, which interpolates from the fine-grid\n # to the coarse-grid. If A is nonsymmetric, then R must be constructed\n # based on A.H. Otherwise R = P.H or P.T.\n symmetry = A.symmetry\n if symmetry == 'hermitian':\n R = P.H\n elif symmetry == 'symmetric':\n R = P.T\n elif symmetry == 'nonsymmetric':\n fn, kwargs = unpack_arg(smooth[len(levels)-1])\n if fn == 'jacobi':\n R = jacobi_prolongation_smoother(AH, TH, C, BH, **kwargs).H\n elif fn == 'richardson':\n R = richardson_prolongation_smoother(AH, TH, **kwargs).H\n elif fn == 'energy':\n R = energy_prolongation_smoother(AH, TH, C, BH, None, (False, {}),\n **kwargs)\n R = R.H\n elif fn is None:\n R = T.H\n else:\n raise ValueError('unrecognized prolongation smoother method %s' %\n str(fn))\n\n if keep:\n levels[-1].C = C # strength of connection matrix\n levels[-1].AggOp = AggOp # aggregation operator\n levels[-1].T = T # tentative prolongator\n\n levels[-1].P = P # smoothed prolongator\n levels[-1].R = R # restriction operator\n\n levels.append(multilevel_solver.level())\n A = R * A * P # Galerkin operator\n A.symmetry = symmetry\n levels[-1].A = A\n levels[-1].B = B # right near nullspace candidates\n\n if A.symmetry == \"nonsymmetric\":\n levels[-1].BH = BH # left near nullspace candidates\n", "\"\"\"VTK output functions.\n\nCreate coarse grid views and write meshes/primitives to .vtu files. Use the\nXML VTK format for unstructured meshes (.vtu)\n\nThis will use the XML VTK format for unstructured meshes, .vtu\n\nSee here for a guide: http://www.vtk.org/pdf/file-formats.pdf\n\"\"\"\nfrom __future__ import print_function\n\nimport xml.dom.minidom\nimport numpy as np\n\n__all__ = ['write_vtu', 'write_basic_mesh']\n\n\ndef write_vtu(Verts, Cells, pdata=None, pvdata=None, cdata=None, cvdata=None,\n fname='output.vtk'):\n \"\"\"Write a .vtu file in xml format.\n\n Parameters\n ----------\n fname : {string}\n file to be written, e.g. 'mymesh.vtu'\n Verts : {array}\n Ndof x 3 (if 2, then expanded by 0)\n list of (x,y,z) point coordinates\n Cells : {dictionary}\n Dictionary of with the keys\n pdata : {array}\n Ndof x Nfields array of scalar values for the vertices\n pvdata : {array}\n Nfields*3 x Ndof array of vector values for the vertices\n cdata : {dictionary}\n scalar valued cell data\n cvdata : {dictionary}\n vector valued cell data\n\n Returns\n -------\n writes a .vtu file for use in Paraview\n\n Notes\n -----\n - Poly data not supported\n - Non-Poly data is stored in Numpy array: Ncell x vtk_cell_info\n - Each I1 must be >=3\n - pdata = Ndof x Nfields\n - pvdata = 3*Ndof x Nfields\n - cdata,cvdata = list of dictionaries in the form of Cells\n\n\n ===== =================== ============= ===\n keys type n points dim\n ===== =================== ============= ===\n 1 VTK_VERTEX: 1 point 2d\n 2 VTK_POLY_VERTEX: n points 2d\n 3 VTK_LINE: 2 points 2d\n 4 VTK_POLY_LINE: n+1 points 2d\n 5 VTK_TRIANGLE: 3 points 2d\n 6 VTK_TRIANGLE_STRIP: n+2 points 2d\n 7 VTK_POLYGON: n points 2d\n 8 VTK_PIXEL: 4 points 2d\n 9 VTK_QUAD: 4 points 2d\n 10 VTK_TETRA: 4 points 3d\n 11 VTK_VOXEL: 8 points 3d\n 12 VTK_HEXAHEDRON: 8 points 3d\n 13 VTK_WEDGE: 6 points 3d\n 14 VTK_PYRAMID: 5 points 3d\n ===== =================== ============= ===\n\n Examples\n --------\n >>> from pyamg.vis import write_vtu\n >>> import numpy as np\n >>> Verts = np.array([[0.0,0.0],\n ... [1.0,0.0],\n ... [2.0,0.0],\n ... [0.0,1.0],\n ... [1.0,1.0],\n ... [2.0,1.0],\n ... [0.0,2.0],\n ... [1.0,2.0],\n ... [2.0,2.0],\n ... [0.0,3.0],\n ... [1.0,3.0],\n ... [2.0,3.0]])\n >>> E2V = np.array([[0,4,3],\n ... [0,1,4],\n ... [1,5,4],\n ... [1,2,5],\n ... [3,7,6],\n ... [3,4,7],\n ... [4,8,7],\n ... [4,5,8],\n ... [6,10,9],\n ... [6,7,10],\n ... [7,11,10],\n ... [7,8,11]])\n >>> E2edge = np.array([[0,1]])\n >>> E2point = np.array([2,3,4,5])\n >>> Cells = {5:E2V,3:E2edge,1:E2point}\n >>> pdata=np.ones((12,2))\n >>> pvdata=np.ones((12*3,2))\n >>> cdata={5:np.ones((12,2)),3:np.ones((1,2)),1:np.ones((4,2))}\n >>> cvdata={5:np.ones((3*12,2)),3:np.ones((3*1,2)),\n 1:np.ones((3*4,2))}\n >>> write_vtu(Verts=Verts, Cells=Cells, fname='test.vtu')\n\n See Also\n --------\n write_mesh\n\n \"\"\"\n # number of indices per cell for each cell type\n vtk_cell_info = [-1, 1, None, 2, None, 3, None, None, 4, 4, 4, 8, 8, 6, 5]\n\n # check fname\n if isinstance(fname, str):\n try:\n fname = open(fname, 'w')\n except IOError as e:\n print(\".vtu error (%s): %s\" % (e.errno, e.strerror))\n else:\n raise ValueError('fname is assumed to be a string')\n\n # check Verts\n # get dimension and verify that it's 3d data\n Ndof, dim = Verts.shape\n if dim == 2:\n # always use 3d coordinates (x,y) -> (x,y,0)\n Verts = np.hstack((Verts, np.zeros((Ndof, 1))))\n\n # check Cells\n # keys must ve valid (integer and not \"None\" in vtk_cell_info)\n # Cell data can't be empty for a non empty key\n for key in Cells:\n if ((not isinstance(key, int)) or (key not in list(range(1, 15)))):\n raise ValueError('cell array must have positive integer keys\\\n in [1,14]')\n if (vtk_cell_info[key] is None) and (Cells[key] is not None):\n # Poly data\n raise NotImplementedError('Poly Data not implemented yet')\n if Cells[key] is None:\n raise ValueError('cell array cannot be empty for\\\n key %d' % (key))\n if np.ndim(Cells[key]) != 2:\n Cells[key] = Cells[key].reshape((Cells[key].size, 1))\n if vtk_cell_info[key] != Cells[key].shape[1]:\n raise ValueError('cell array has %d columns, expected %d' %\n (Cells[key].shape[1], vtk_cell_info[key]))\n\n # check pdata\n # must be Ndof x n_pdata\n n_pdata = 0\n if pdata is not None:\n if np.ndim(pdata) > 1:\n n_pdata = pdata.shape[1]\n else:\n n_pdata = 1\n pdata = pdata.reshape((pdata.size, 1))\n if pdata.shape[0] != Ndof:\n raise ValueError('pdata array should be length %d (it is %d)' %\n (Ndof, pdata.shape[0]))\n\n # check pvdata\n # must be 3*Ndof x n_pvdata\n n_pvdata = 0\n if pvdata is not None:\n if np.ndim(pvdata) > 1:\n n_pvdata = pvdata.shape[1]\n else:\n n_pvdata = 1\n pvdata = pvdata.reshape((pvdata.size, 1))\n if pvdata.shape[0] != 3*Ndof:\n raise ValueError('pvdata array should be of size %d (or multiples)\\\n (it is now %d)' % (Ndof*3, pvdata.shape[0]))\n\n # check cdata\n # must be NCells x n_cdata for each key\n n_cdata = 0\n if cdata is not None:\n for key in Cells: # all valid now\n if np.ndim(cdata[key]) > 1:\n if n_cdata == 0:\n n_cdata = cdata[key].shape[1]\n elif n_cdata != cdata[key].shape[1]:\n raise ValueError('cdata dimension problem')\n else:\n n_cdata = 1\n cdata[key] = cdata[key].reshape((cdata[key].size, 1))\n if cdata[key].shape[0] != Cells[key].shape[0]:\n raise ValueError('size mismatch with cdata %d and Cells %d' %\n (cdata[key].shape[0], Cells[key].shape[0]))\n if cdata[key] is None:\n raise ValueError('cdata array cannot be empty for key %d' %\n (key))\n\n # check cvdata\n # must be NCells*3 x n_cdata for each key\n n_cvdata = 0\n if cvdata is not None:\n for key in Cells: # all valid now\n if np.ndim(cvdata[key]) > 1:\n if n_cvdata == 0:\n n_cvdata = cvdata[key].shape[1]\n elif n_cvdata != cvdata[key].shape[1]:\n raise ValueError('cvdata dimension problem')\n else:\n n_cvdata = 1\n cvdata[key] = cvdata[key].reshape((cvdata[key].size, 1))\n if cvdata[key].shape[0] != 3*Cells[key].shape[0]:\n raise ValueError('size mismatch with cvdata and Cells')\n if cvdata[key] is None:\n raise ValueError('cvdata array cannot be empty for key %d' %\n (key))\n\n Ncells = 0\n cell_ind = []\n cell_offset = [] # np.zeros((Ncells,1),dtype=uint8) # zero indexed\n cell_type = [] # np.zeros((Ncells,1),dtype=uint8)\n\n cdata_all = None\n cvdata_all = None\n for key in Cells:\n # non-Poly data\n sz = Cells[key].shape[0]\n offset = Cells[key].shape[1]\n\n Ncells += sz\n uu = np.ones((sz,), dtype='uint8')\n cell_ind = np.hstack((cell_ind, Cells[key].ravel()))\n cell_offset = np.hstack((cell_offset, offset*uu))\n cell_type = np.hstack((cell_type, key*uu))\n\n if cdata is not None:\n if cdata_all is None:\n cdata_all = cdata[key]\n else:\n cdata_all = np.vstack((cdata_all, cdata[key]))\n\n if cvdata is not None:\n if cvdata_all is None:\n cvdata_all = cvdata[key]\n else:\n cvdata_all = np.vstack((cvdata_all, cvdata[key]))\n\n # doc element\n doc = xml.dom.minidom.Document()\n\n # vtk element\n root = doc.createElementNS('VTK', 'VTKFile')\n d = {'type': 'UnstructuredGrid', 'version': '0.1',\n 'byte_order': 'LittleEndian'}\n set_attributes(d, root)\n\n # unstructured element\n grid = doc.createElementNS('VTK', 'UnstructuredGrid')\n\n # piece element\n piece = doc.createElementNS('VTK', 'Piece')\n d = {'NumberOfPoints': str(Ndof), 'NumberOfCells': str(Ncells)}\n set_attributes(d, piece)\n\n # POINTS\n # points element\n points = doc.createElementNS('VTK', 'Points')\n # data element\n points_data = doc.createElementNS('VTK', 'DataArray')\n d = {'type': 'Float32', 'Name': 'vertices', 'NumberOfComponents': '3',\n 'format': 'ascii'}\n set_attributes(d, points_data)\n # string for data element\n points_data_str = doc.createTextNode(a2s(Verts))\n\n # CELLS\n # points element\n cells = doc.createElementNS('VTK', 'Cells')\n # data element\n cells_data = doc.createElementNS('VTK', 'DataArray')\n d = {'type': 'Int32', 'Name': 'connectivity', 'format': 'ascii'}\n set_attributes(d, cells_data)\n # string for data element\n cells_data_str = doc.createTextNode(a2s(cell_ind))\n # offset data element\n cells_offset_data = doc.createElementNS('VTK', 'DataArray')\n d = {'type': 'Int32', 'Name': 'offsets', 'format': 'ascii'}\n set_attributes(d, cells_offset_data)\n # string for data element\n cells_offset_data_str = doc.createTextNode(a2s(cell_offset.cumsum()))\n # offset data element\n cells_type_data = doc.createElementNS('VTK', 'DataArray')\n d = {'type': 'UInt8', 'Name': 'types', 'format': 'ascii'}\n set_attributes(d, cells_type_data)\n # string for data element\n cells_type_data_str = doc.createTextNode(a2s(cell_type))\n\n # POINT DATA\n pointdata = doc.createElementNS('VTK', 'PointData')\n # pdata\n pdata_obj = []\n pdata_str = []\n for i in range(0, n_pdata):\n pdata_obj.append(doc.createElementNS('VTK', 'DataArray'))\n d = {'type': 'Float32', 'Name': 'pdata %d' % (i),\n 'NumberOfComponents': '1', 'format': 'ascii'}\n set_attributes(d, pdata_obj[i])\n pdata_str.append(doc.createTextNode(a2s(pdata[:, i])))\n # pvdata\n pvdata_obj = []\n pvdata_str = []\n for i in range(0, n_pvdata):\n pvdata_obj.append(doc.createElementNS('VTK', 'DataArray'))\n d = {'type': 'Float32', 'Name': 'pvdata %d' % (i),\n 'NumberOfComponents': '3', 'format': 'ascii'}\n set_attributes(d, pvdata_obj[i])\n pvdata_str.append(doc.createTextNode(a2s(pvdata[:, i])))\n\n # CELL DATA\n celldata = doc.createElementNS('VTK', 'CellData')\n # cdata\n cdata_obj = []\n cdata_str = []\n for i in range(0, n_cdata):\n cdata_obj.append(doc.createElementNS('VTK', 'DataArray'))\n d = {'type': 'Float32', 'Name': 'cdata %d' % (i),\n 'NumberOfComponents': '1', 'format': 'ascii'}\n set_attributes(d, cdata_obj[i])\n cdata_str.append(doc.createTextNode(a2s(cdata_all[:, i])))\n # cvdata\n cvdata_obj = []\n cvdata_str = []\n for i in range(0, n_cvdata):\n cvdata_obj.append(doc.createElementNS('VTK', 'DataArray'))\n d = {'type': 'Float32', 'Name': 'cvdata %d' % (i),\n 'NumberOfComponents': '3', 'format': 'ascii'}\n set_attributes(d, cvdata_obj[i])\n cvdata_str.append(doc.createTextNode(a2s(cvdata_all[:, i])))\n\n doc.appendChild(root)\n root.appendChild(grid)\n grid.appendChild(piece)\n\n piece.appendChild(points)\n points.appendChild(points_data)\n points_data.appendChild(points_data_str)\n\n piece.appendChild(cells)\n cells.appendChild(cells_data)\n cells.appendChild(cells_offset_data)\n cells.appendChild(cells_type_data)\n cells_data.appendChild(cells_data_str)\n cells_offset_data.appendChild(cells_offset_data_str)\n cells_type_data.appendChild(cells_type_data_str)\n\n piece.appendChild(pointdata)\n for i in range(0, n_pdata):\n pointdata.appendChild(pdata_obj[i])\n pdata_obj[i].appendChild(pdata_str[i])\n for i in range(0, n_pvdata):\n pointdata.appendChild(pvdata_obj[i])\n pvdata_obj[i].appendChild(pvdata_str[i])\n\n piece.appendChild(celldata)\n for i in range(0, n_cdata):\n celldata.appendChild(cdata_obj[i])\n cdata_obj[i].appendChild(cdata_str[i])\n for i in range(0, n_cvdata):\n celldata.appendChild(cvdata_obj[i])\n cvdata_obj[i].appendChild(cvdata_str[i])\n\n doc.writexml(fname, newl='\\n')\n fname.close()\n\n\ndef write_basic_mesh(Verts, E2V=None, mesh_type='tri',\n pdata=None, pvdata=None,\n cdata=None, cvdata=None, fname='output.vtk'):\n \"\"\"Write mesh file for basic types of elements.\n\n Parameters\n ----------\n fname : {string}\n file to be written, e.g. 'mymesh.vtu'\n Verts : {array}\n coordinate array (N x D)\n E2V : {array}\n element index array (Nel x Nelnodes)\n mesh_type : {string}\n type of elements: tri, quad, tet, hex (all 3d)\n pdata : {array}\n scalar data on vertices (N x Nfields)\n pvdata : {array}\n vector data on vertices (3*Nfields x N)\n cdata : {array}\n scalar data on cells (Nfields x Nel)\n cvdata : {array}\n vector data on cells (3*Nfields x Nel)\n\n Returns\n -------\n writes a .vtu file for use in Paraview\n\n Notes\n -----\n The difference between write_basic_mesh and write_vtu is that write_vtu is\n more general and requires dictionaries of cell information.\n write_basic_mesh calls write_vtu\n\n Examples\n --------\n >>> import numpy as np\n >>> from pyamg.vis import write_basic_mesh\n >>> Verts = np.array([[0.0,0.0],\n ... [1.0,0.0],\n ... [2.0,0.0],\n ... [0.0,1.0],\n ... [1.0,1.0],\n ... [2.0,1.0],\n ... [0.0,2.0],\n ... [1.0,2.0],\n ... [2.0,2.0],\n ... [0.0,3.0],\n ... [1.0,3.0],\n ... [2.0,3.0]])\n >>> E2V = np.array([[0,4,3],\n ... [0,1,4],\n ... [1,5,4],\n ... [1,2,5],\n ... [3,7,6],\n ... [3,4,7],\n ... [4,8,7],\n ... [4,5,8],\n ... [6,10,9],\n ... [6,7,10],\n ... [7,11,10],\n ... [7,8,11]])\n >>> pdata=np.ones((12,2))\n >>> pvdata=np.ones((12*3,2))\n >>> cdata=np.ones((12,2))\n >>> cvdata=np.ones((3*12,2))\n >>> write_basic_mesh(Verts, E2V=E2V, mesh_type='tri',pdata=pdata,\n pvdata=pvdata, cdata=cdata, cvdata=cvdata,\n fname='test.vtu')\n\n See Also\n --------\n write_vtu\n\n \"\"\"\n if E2V is None:\n mesh_type = 'vertex'\n\n map_type_to_key = {'vertex': 1, 'tri': 5, 'quad': 9, 'tet': 10, 'hex': 12}\n\n if mesh_type not in map_type_to_key:\n raise ValueError('unknown mesh_type=%s' % mesh_type)\n\n key = map_type_to_key[mesh_type]\n\n if mesh_type == 'vertex':\n uidx = np.arange(0, Verts.shape[0]).reshape((Verts.shape[0], 1))\n E2V = {key: uidx}\n else:\n E2V = {key: E2V}\n\n if cdata is not None:\n cdata = {key: cdata}\n\n if cvdata is not None:\n cvdata = {key: cvdata}\n\n write_vtu(Verts=Verts, Cells=E2V, pdata=pdata, pvdata=pvdata,\n cdata=cdata, cvdata=cvdata, fname=fname)\n\n\ndef set_attributes(d, elm):\n \"\"\"Set attributes from dictionary of values.\"\"\"\n for key in d:\n elm.setAttribute(key, d[key])\n\n\ndef a2s(a):\n \"\"\"Convert to string.\"\"\"\n str = ''\n return str.join(['%g ' % (v) for v in a.ravel()])\n" ]
[ [ "numpy.asarray", "scipy.sparse.csr_matrix", "scipy.sparse.isspmatrix_bsr", "scipy.sparse.isspmatrix_csr", "numpy.zeros" ], [ "numpy.hstack", "numpy.arange", "numpy.ones", "numpy.ndim", "numpy.zeros", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MuellerSeb/jams_python
[ "1bca04557da79d8f8a4c447f5ccc517c40ab7dfc", "1bca04557da79d8f8a4c447f5ccc517c40ab7dfc", "1bca04557da79d8f8a4c447f5ccc517c40ab7dfc", "1bca04557da79d8f8a4c447f5ccc517c40ab7dfc", "1bca04557da79d8f8a4c447f5ccc517c40ab7dfc", "1bca04557da79d8f8a4c447f5ccc517c40ab7dfc" ]
[ "jams/errormeasures.py", "jams/str2tex.py", "jams/eddybox/energyclosure.py", "jams/eddybox/sltclean.py", "jams/ascii2ascii.py", "jams/eddybox/profile2storage.py" ]
[ "#!/usr/bin/env python\nfrom __future__ import division, absolute_import, print_function\nimport numpy as np\nfrom scipy.stats import t\n\n\"\"\"\n Defines common error measures.\n\n \n Definition\n ----------\n def bias(y_obs,y_mod): bias\n def mae(y_obs,y_mod): mean absolute error\n def mse(y_obs,y_mod): mean squared error\n def rmse(y_obs,y_mod): root mean squared error\n def nse(y_obs,y_mod): Nash-Sutcliffe-Efficiency\n def kge(y_obs,y_mod): Kling-Gupta-Efficiency\n def pear2(y_obs,y_mod): Squared Pearson correlation coefficient\n def confint(y_obs, p=0.95): Confidence interval of samples\n \n\n Input\n -----\n y_obs np.array(N) or np.ma.array(N)\n y_mod np.array(N) or np.ma.array(N)\n\n\n Output\n ------\n measure float: error measure of respective error function\n (see definitions for details)\n\n Restrictions\n ------------\n Deals with masked and unmasked arrays. When nan is found in an unmasked\n array, it will be masked. All measures are applied only on values where\n both, y_obs and y_mod, have valid entries (not masked and not nan)\n \n \n Examples\n --------\n -> see respective function\n\n\n License\n -------\n This file is part of the JAMS Python package, distributed under the MIT\n License. The JAMS Python package originates from the former UFZ Python library,\n Department of Computational Hydrosystems, Helmholtz Centre for Environmental\n Research - UFZ, Leipzig, Germany.\n\n Copyright (c) 2014-2017 Arndt Piayda, Stephan Thober, Matthias Cuntz - mc (at) macu (dot) de\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n\n History\n -------\n Written, AP, Jul 2014\n Modified MC, Dec 2014 - use simple formulas that work with normal and masked arrays but do not deal with NaN\n Modified AP, Sep 2015 - add confidence interval\n Modified ST, Nov 2015 - added KGE\n Modified ST, Jan 2017 - added components for KGE\n\"\"\"\n\ndef bias(y_obs,y_mod):\n \"\"\"\n calculates bias = mean(y_obs) - mean(y_mod)\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])\n >>> # calculate bias\n >>> print(np.round(bias(y_obs, y_mod),2))\n -0.43\n\n \"\"\"\n # # check\n # if (y_obs.ndim!=1) or (y_mod.ndim!=1):\n # raise ValueError('bias: input must be 1D')\n # elif y_obs.size!=y_mod.size:\n # raise ValueError('bias: input must be of same size')\n # # calc\n # else:\n # # check if masked or not\n # try:\n # temp = y_obs.mask\n # temp = y_mod.mask\n # except AttributeError:\n # y_obs=np.ma.array(y_obs, mask=np.isnan(y_obs))\n # y_mod=np.ma.array(y_mod, mask=np.isnan(y_mod))\n # y_modr = np.ma.array(y_mod, mask=y_mod.mask | y_obs.mask) \n # y_obsr = np.ma.array(y_obs, mask=y_mod.mask | y_obs.mask)\n # return np.ma.mean(y_obsr) - np.ma.mean(y_modr)\n return y_obs.mean() - y_mod.mean()\n\ndef mae(y_obs,y_mod):\n \"\"\"\n calculates mean absolute error = mean(abs(y_obs - y_mod))\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])\n >>> # calculate mean absolute error\n >>> print(np.round(mae(y_obs, y_mod),2))\n 0.55\n\n \"\"\"\n # check\n if (y_obs.ndim!=1) or (y_mod.ndim!=1):\n raise ValueError('mae: input must be 1D')\n elif y_obs.size!=y_mod.size:\n raise ValueError('mae: input must be of same size')\n # calc\n else:\n # check if masked or not\n try:\n temp = y_obs.mask\n temp = y_mod.mask\n except AttributeError:\n y_obs=np.ma.array(y_obs, mask=np.isnan(y_obs))\n y_mod=np.ma.array(y_mod, mask=np.isnan(y_mod))\n y_modr = np.ma.array(y_mod, mask=y_mod.mask | y_obs.mask) \n y_obsr = np.ma.array(y_obs, mask=y_mod.mask | y_obs.mask)\n return np.ma.mean(np.ma.abs(y_obsr-y_modr))\n\ndef mse(y_obs,y_mod):\n \"\"\"\n calculates mean squared error = mean((y_obs - y_mod)**2)\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])\n >>> # calculate mean squared error\n >>> print(np.round(mse(y_obs, y_mod),2))\n 0.54\n\n \"\"\"\n # # check\n # if (y_obs.ndim!=1) or (y_mod.ndim!=1):\n # raise ValueError('mse: input must be 1D')\n # elif y_obs.size!=y_mod.size:\n # raise ValueError('mse: input must be of same size')\n # # calc\n # else:\n # # check if masked or not\n # try:\n # temp = y_obs.mask\n # temp = y_mod.mask\n # except AttributeError:\n # y_obs=np.ma.array(y_obs, mask=np.isnan(y_obs))\n # y_mod=np.ma.array(y_mod, mask=np.isnan(y_mod))\n # y_modr = np.ma.array(y_mod, mask=y_mod.mask | y_obs.mask) \n # y_obsr = np.ma.array(y_obs, mask=y_mod.mask | y_obs.mask)\n # return np.ma.mean((y_obsr-y_modr)**2)\n return ((y_obs-y_mod)**2).mean()\n\ndef rmse(y_obs,y_mod):\n \"\"\"\n calculates root mean squared error = sqrt(mean((y_obs - y_mod)**2))\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])\n >>> # calculate root mean squared error\n >>> print(np.round(rmse(y_obs, y_mod),2))\n 0.73\n\n \"\"\"\n # # check\n # if (y_obs.ndim!=1) or (y_mod.ndim!=1):\n # raise ValueError('rmse: input must be 1D')\n # elif y_obs.size!=y_mod.size:\n # raise ValueError('rmse: input must be of same size')\n # # calc\n # else:\n # # check if masked or not\n # try:\n # temp = y_obs.mask\n # temp = y_mod.mask\n # except AttributeError:\n # y_obs=np.ma.array(y_obs, mask=np.isnan(y_obs))\n # y_mod=np.ma.array(y_mod, mask=np.isnan(y_mod))\n # y_modr = np.ma.array(y_mod, mask=y_mod.mask | y_obs.mask)\n # y_obsr = np.ma.array(y_obs, mask=y_mod.mask | y_obs.mask)\n # return np.ma.sqrt(np.ma.mean((y_obsr-y_modr)**2))\n return ((y_obs-y_mod)**2).mean()**0.5\n\ndef nse(y_obs,y_mod):\n \"\"\"\n calculates Nash-Sutcliffe-Efficiency = 1 - (sum((y_obs - y_mod)**2) / sum((y_obs - mean(y_obs))**2))\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])\n >>> # calculate Nash-Sutcliffe-Efficiency\n >>> print(np.round(nse(y_obs, y_mod),2))\n 0.71\n\n \"\"\"\n # # check\n # if (y_obs.ndim!=1) or (y_mod.ndim!=1):\n # raise ValueError('r2: input must be 1D')\n # elif y_obs.size!=y_mod.size:\n # raise ValueError('r2: input must be of same size')\n # # calc\n # else:\n # # check if masked or not\n # try:\n # temp = y_obs.mask\n # temp = y_mod.mask\n # except AttributeError:\n # y_obs=np.ma.array(y_obs, mask=np.isnan(y_obs))\n # y_mod=np.ma.array(y_mod, mask=np.isnan(y_mod))\n # y_modr = np.ma.array(y_mod, mask=y_mod.mask | y_obs.mask) \n # y_obsr = np.ma.array(y_obs, mask=y_mod.mask | y_obs.mask)\n # a = np.ma.sum((y_obsr - y_modr)**2)\n # b = np.ma.sum((y_obsr - np.ma.mean(y_obsr))**2)\n # return 1. - (a / b)\n return 1. - ((y_obs-y_mod)**2).sum()/((y_obs-y_obs.mean())**2).sum()\n\n\ndef kge(y_obs,y_mod,components=False):\n \"\"\"\n calculates Kling-Gupta-Efficiency = 1 - sqrt((1-r)**2 + (1-a)**2 + (1-b)**2),\n where r is the Pearson correlation of y_obs and y_mod,\n a is mean(y_mod) / mean(y_obs), and\n b is std(y_mod) / std(y_obs)\n if components is True, then r, a, and b are (in this order) additionally returned to the KGE\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])\n >>> # calculate Kling-Gupta-Efficiency\n >>> print(np.round(kge(y_obs, y_mod),2))\n 0.58\n\n \"\"\"\n # # check\n # if (y_obs.ndim!=1) or (y_mod.ndim!=1):\n # raise ValueError('r2: input must be 1D')\n # elif y_obs.size!=y_mod.size:\n # raise ValueError('r2: input must be of same size')\n # # calc\n # else:\n # # check if masked or not\n # try:\n # temp = y_obs.mask\n # temp = y_mod.mask\n # except AttributeError:\n # y_obs=np.ma.array(y_obs, mask=np.isnan(y_obs))\n # y_mod=np.ma.array(y_mod, mask=np.isnan(y_mod))\n # y_modr = np.ma.array(y_mod, mask=y_mod.mask | y_obs.mask) \n # y_obsr = np.ma.array(y_obs, mask=y_mod.mask | y_obs.mask)\n # r = np.ma.corrcoef(y_obsr, y_modr)[0, 1]\n # a = np.ma.mean(y_modr) / np.ma.mean(y_obsr)\n # b = np.ma.std(y_modr) / np.ma.std(y_obsr)\n # return 1. - np.sqrt((1 - r)**2 + (1 - a)**2 + (1 - b)**2)\n r = np.corrcoef(y_obs, y_mod)[0, 1]\n alpha = np.std(y_mod) / np.std(y_obs)\n beta = np.mean(y_mod) / np.mean(y_obs)\n if components:\n return 1. - np.sqrt((1 - r)**2 + (1 - beta)**2 + (1 - alpha)**2), r, alpha, beta\n else:\n return 1. - np.sqrt((1 - r)**2 + (1 - beta)**2 + (1 - alpha)**2)\n\n\ndef pear2(y_obs,y_mod):\n \"\"\"\n calculates squared Pearson correlation coeffcient\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> y_mod = np.array([12.8087, 13.151, 14.3741, 16.2302, 17.9433])\n >>> # calculate Squared Pearson correlation coefficient\n >>> print(np.round(pear2(y_obs, y_mod),2))\n 0.99\n\n \"\"\"\n # # check\n # if (y_obs.ndim!=1) or (y_mod.ndim!=1):\n # raise ValueError('pear2: input must be 1D')\n # elif y_obs.size!=y_mod.size:\n # raise ValueError('pear2: input must be of same size')\n # # calc\n # else:\n # # check if masked or not\n # try:\n # temp = y_obs.mask\n # temp = y_mod.mask\n # except AttributeError:\n # y_obs=np.ma.array(y_obs, mask=np.isnan(y_obs))\n # y_mod=np.ma.array(y_mod, mask=np.isnan(y_mod))\n # y_modr = np.ma.array(y_mod, mask=y_mod.mask | y_obs.mask) \n # y_obsr = np.ma.array(y_obs, mask=y_mod.mask | y_obs.mask) \n # return np.corrcoef(y_obsr.compressed(), y_modr.compressed())[0,1]**2\n return ((y_obs-y_obs.mean())*(y_mod-y_mod.mean())).mean()/y_obs.std()/y_mod.std()\n \ndef confint(y_obs, p=0.95):\n \"\"\"\n calculates confidence interval of the mean of the sample applying a \n student-t-distribution to a given probability p (default p=0.95)\n \n Examples\n --------\n >>> # Create some data\n >>> y_obs = np.array([12.7867, 13.465, 14.1433, 15.3733, 16.6033])\n >>> # calculate confident interval\n >>> print(np.round(confint(y_obs)))\n [13. 16.]\n\n \"\"\"\n s = y_obs.size\n return np.array(t.interval(p, s-1., loc=y_obs.mean(), scale=y_obs.std()/np.sqrt(s)))\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n", "#!/usr/bin/env python\nfrom __future__ import division, absolute_import, print_function\nimport numpy as np\n\n__all__ = ['str2tex']\n\ndef str2tex(strin, space2linebreak=False, bold=False, italic=False, usetex=True):\n \"\"\"\n Convert strings to LaTeX strings in math environement used by matplotlib's usetex.\n\n Strings are embedded into $\\mathrm{strin}$ be default but can be embedded into\n \\mathbf and \\mathit.\n Spaces are escaped but can be replaced by linebreaks.\n \n \n Definition\n ----------\n def str2tex(strin, space2linebreak=False, bold=False, italic=False):\n\n\n Input\n -----\n list/ND-array of strings\n\n\n Optional Input\n --------------\n space2linebreak True: replace space (' ') by linebreak ('\\n')\n bold True: use \\mathbf\n italic True: use \\mathit\n usetex False: do only space2linebreak otherwise nothing\n\n\n Output\n ------\n list/ND-array of strings that can be used in plots independent of usetex.\n\n\n Examples\n --------\n # replace all \\ by \\\\ in docstring in- and outputs\n >>> strin = ['One', 'One-', 'One-Two', 'One Two', 'One\\\\nTwo', 'A $S_{Ti}$ is great\\\\nbut use-less']\n >>> print(str2tex(strin))\n ['$\\\\\\\\mathrm{One}$', '$\\\\\\\\mathrm{One}$$\\\\\\\\textrm{-}$', '$\\\\\\\\mathrm{One}$$\\\\\\\\textrm{-}$$\\\\\\\\mathrm{Two}$', '$\\\\\\\\mathrm{One\\\\\\\\ Two}$', '$\\\\\\\\mathrm{One}$ \\\\n $\\\\\\\\mathrm{Two}$', '$\\\\\\\\mathrm{A\\\\\\\\ }$$S_{Ti}$$\\\\\\\\mathrm{\\\\\\\\ is\\\\\\\\ great}$ \\\\n $\\\\\\\\mathrm{but\\\\\\\\ use}$$\\\\\\\\textrm{-}$$\\\\\\\\mathrm{less}$']\n >>> print(str2tex(strin, bold=True))\n ['$\\\\\\\\mathbf{One}$', '$\\\\\\\\mathbf{One}$$\\\\\\\\textbf{-}$', '$\\\\\\\\mathbf{One}$$\\\\\\\\textbf{-}$$\\\\\\\\mathbf{Two}$', '$\\\\\\\\mathbf{One\\\\\\\\ Two}$', '$\\\\\\\\mathbf{One}$ \\\\n $\\\\\\\\mathbf{Two}$', '$\\\\\\\\mathbf{A\\\\\\\\ }$$S_{Ti}$$\\\\\\\\mathbf{\\\\\\\\ is\\\\\\\\ great}$ \\\\n $\\\\\\\\mathbf{but\\\\\\\\ use}$$\\\\\\\\textbf{-}$$\\\\\\\\mathbf{less}$']\n >>> print(str2tex(strin, italic=True))\n ['$\\\\\\\\mathit{One}$', '$\\\\\\\\mathit{One}$$\\\\\\\\textit{-}$', '$\\\\\\\\mathit{One}$$\\\\\\\\textit{-}$$\\\\\\\\mathit{Two}$', '$\\\\\\\\mathit{One\\\\\\\\ Two}$', '$\\\\\\\\mathit{One}$ \\\\n $\\\\\\\\mathit{Two}$', '$\\\\\\\\mathit{A\\\\\\\\ }$$S_{Ti}$$\\\\\\\\mathit{\\\\\\\\ is\\\\\\\\ great}$ \\\\n $\\\\\\\\mathit{but\\\\\\\\ use}$$\\\\\\\\textit{-}$$\\\\\\\\mathit{less}$']\n >>> print(str2tex(strin, space2linebreak=True))\n ['$\\\\\\\\mathrm{One}$', '$\\\\\\\\mathrm{One}$$\\\\\\\\textrm{-}$', '$\\\\\\\\mathrm{One}$$\\\\\\\\textrm{-}$$\\\\\\\\mathrm{Two}$', '$\\\\\\\\mathrm{One}$ \\\\n $\\\\\\\\mathrm{Two}$', '$\\\\\\\\mathrm{One}$ \\\\n $\\\\\\\\mathrm{Two}$', '$\\\\\\\\mathrm{A}$ \\\\n $\\\\\\\\mathrm{}$$S_{Ti}$$\\\\\\\\mathrm{ \\\\n $\\\\\\\\mathrm{is \\\\n $\\\\\\\\mathrm{great}$ \\\\n $\\\\\\\\mathrm{but \\\\n $\\\\\\\\mathrm{use}$$\\\\\\\\textrm{-}$$\\\\\\\\mathrm{less}$']\n >>> print(str2tex(strin, space2linebreak=True, bold=True))\n ['$\\\\\\\\mathbf{One}$', '$\\\\\\\\mathbf{One}$$\\\\\\\\textbf{-}$', '$\\\\\\\\mathbf{One}$$\\\\\\\\textbf{-}$$\\\\\\\\mathbf{Two}$', '$\\\\\\\\mathbf{One}$ \\\\n $\\\\\\\\mathbf{Two}$', '$\\\\\\\\mathbf{One}$ \\\\n $\\\\\\\\mathbf{Two}$', '$\\\\\\\\mathbf{A}$ \\\\n $\\\\\\\\mathbf{}$$S_{Ti}$$\\\\\\\\mathbf{ \\\\n $\\\\\\\\mathbf{is \\\\n $\\\\\\\\mathbf{great}$ \\\\n $\\\\\\\\mathbf{but \\\\n $\\\\\\\\mathbf{use}$$\\\\\\\\textbf{-}$$\\\\\\\\mathbf{less}$']\n >>> print(str2tex(strin, usetex=False))\n ['One', 'One-', 'One-Two', 'One Two', 'One\\\\nTwo', 'A $S_{Ti}$ is great\\\\nbut use-less']\n >>> print(str2tex(strin, space2linebreak=True, usetex=False))\n ['One', 'One-', 'One-Two', 'One\\\\nTwo', 'One\\\\nTwo', 'A\\\\n$S_{Ti}$\\\\nis\\\\ngreat\\\\nbut\\\\nuse-less']\n\n\n License\n -------\n This file is part of the JAMS Python package, distributed under the MIT\n License. The JAMS Python package originates from the former UFZ Python library,\n Department of Computational Hydrosystems, Helmholtz Centre for Environmental\n Research - UFZ, Leipzig, Germany.\n\n Copyright (c) 2015 Matthias Cuntz - mc (at) macu (dot) de\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n\n History\n -------\n Written, MC, Oct 2015\n \"\"\"\n\n # Input type and shape\n if isinstance(strin, list):\n from copy import copy\n istrin = copy(strin)\n elif isinstance(strin, tuple):\n istrin = list(strin)\n elif isinstance(strin, np.ndarray):\n istrin = list(strin.flatten())\n else:\n istrin = [strin]\n # nstrin = len(istrin)\n\n # font style\n if (bold+italic) > 1:\n raise ValueError('bold and italic are mutually exclusive.')\n else:\n if bold:\n mtex = r'$\\mathbf{'\n ttex = r'$\\textbf{'\n elif italic:\n mtex = r'$\\mathit{'\n ttex = r'$\\textit{'\n else: \n mtex = r'$\\mathrm{'\n ttex = r'$\\textrm{'\n\n # helpers\n a0 = chr(0) # ascii 0\n # string replacements\n rep_n = lambda s : s.replace('\\n', '}$'+a0+'\\n'+a0+mtex)\n rep_down = lambda s : s.replace('_', '\\_')\n rep_up = lambda s : s.replace('^', '\\^')\n rep_hash = lambda s : s.replace('#', '\\#')\n rep_percent = lambda s : s.replace('%', '\\%')\n rep_space = lambda s : s.replace(' ', '\\ ')\n rep_minus = lambda s : s.replace('-', '}$'+ttex+'-}$'+mtex)\n rep_a02space = lambda s : s.replace(a0, ' ')\n rep_space2n = lambda s : s.replace(' ', '\\n')\n if usetex:\n for j, s in enumerate(istrin):\n if '$' in s:\n # -, _, ^ only escaped if not between $\n ss = s.split('$')\n for ii in range(0,len(ss),2):\n ss[ii] = mtex+ss[ii]+'}$'\n # - not minus sign\n if '-' in ss[ii]:\n ss[ii] = rep_minus(ss[ii])\n if ss[ii].endswith('{}$'): ss[ii] = ss[ii][:-11] # remove trailing $\\mathrm{}$\n # \\n not in tex mode but normal matplotlib\n if '\\n' in ss[ii]: ss[ii] = rep_n(ss[ii])\n # escape _\n if '_' in ss[ii]: ss[ii] = rep_down(ss[ii])\n # escape ^\n if '^' in ss[ii]: ss[ii] = rep_up(ss[ii])\n # escape #\n if '#' in ss[ii]: ss[ii] = rep_hash(ss[ii])\n # escape %\n if ('%' in ss[ii]) and not ('\\%' in ss[ii]) : ss[ii] = rep_percent(ss[ii])\n istrin[j] = '$'.join(ss)\n if s[0] == '$': istrin[j] = istrin[j][11:] # remove leading $\\mathrm{}$ if started with $\n else:\n istrin[j] = mtex+s+'}$'\n # - not minus sign\n if '-' in istrin[j]:\n istrin[j] = rep_minus(istrin[j])\n if istrin[j].endswith('{}$'): istrin[j] = istrin[j][:-11] # remove trailing $\\mathrm{}$\n # \\n not in tex mode but normal matplotlib\n if '\\n' in istrin[j]: istrin[j] = rep_n(istrin[j])\n # escape _\n if '_' in istrin[j]: istrin[j] = rep_down(istrin[j])\n # escape ^\n if '^' in istrin[j]: istrin[j] = rep_up(istrin[j])\n # escape #\n if '#' in istrin[j]: istrin[j] = rep_hash(istrin[j])\n # escape %\n if ('%' in istrin[j]) and not ('\\%' in istrin[j]): istrin[j] = rep_percent(istrin[j])\n\n # escape space or linebreak at space\n if ' ' in istrin[j]:\n if space2linebreak:\n # line break\n ic = istrin[j].split(' ')\n for ii, iic in enumerate(ic):\n if ii==0:\n istrin[j] = iic + '}$'\n else:\n istrin[j] = istrin[j] + a0 + '\\n' + a0 + mtex+ iic\n else: \n # escaped space \n istrin[j] = rep_space(istrin[j])\n # rm ascii character 0 around linebreaks introduced above\n if a0 in istrin[j]: istrin[j] = rep_a02space(istrin[j])\n else:\n # escape %\n if ('%' in istrin) and not ('\\%' in istrin): istrin = rep_percent(istrin)\n if space2linebreak: istrin = [ rep_space2n(i) for i in istrin ]\n\n # Return right type\n if isinstance(strin, list):\n return istrin\n elif isinstance(strin, tuple):\n return tuple(istrin)\n elif isinstance(strin, np.ndarray):\n return np.array(istrin).reshape(strin.shape)\n else:\n return istrin[0]\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)\n\n # strin = ['One', 'One-', 'One-Two', 'One Two', 'One\\nTwo', 'A $S_{Ti}$ is great\\nbut use-less']\n # print(str2tex(strin))\n # # ['$\\\\mathrm{One}$', '$\\\\mathrm{One}$$\\\\textrm{-}$', '$\\\\mathrm{One}$$\\\\textrm{-}$$\\\\mathrm{Two}$', '$\\\\mathrm{One\\\\ Two}$', '$\\\\mathrm{One}$ \\n $\\\\mathrm{Two}$', '$\\\\mathrm{A\\\\ }$$S_{Ti}$$\\\\mathrm{\\\\ is\\\\ great}$ \\n $\\\\mathrm{but\\\\ use}$$\\\\textrm{-}$$\\\\mathrm{less}$']\n # print(str2tex(strin, bold=True))\n # # ['$\\\\mathbf{One}$', '$\\\\mathbf{One}$$\\\\textbf{-}$', '$\\\\mathbf{One}$$\\\\textbf{-}$$\\\\mathbf{Two}$', '$\\\\mathbf{One\\\\ Two}$', '$\\\\mathbf{One}$ \\n $\\\\mathbf{Two}$', '$\\\\mathbf{A\\\\ }$$S_{Ti}$$\\\\mathbf{\\\\ is\\\\ great}$ \\n $\\\\mathbf{but\\\\ use}$$\\\\textbf{-}$$\\\\mathbf{less}$']\n # print(str2tex(strin, italic=True))\n # # ['$\\\\mathit{One}$', '$\\\\mathit{One}$$\\\\textit{-}$', '$\\\\mathit{One}$$\\\\textit{-}$$\\\\mathit{Two}$', '$\\\\mathit{One\\\\ Two}$', '$\\\\mathit{One}$ \\n $\\\\mathit{Two}$', '$\\\\mathit{A\\\\ }$$S_{Ti}$$\\\\mathit{\\\\ is\\\\ great}$ \\n $\\\\mathit{but\\\\ use}$$\\\\textit{-}$$\\\\mathit{less}$']\n # print(str2tex(strin, space2linebreak=True))\n # # ['$\\\\mathrm{One}$', '$\\\\mathrm{One}$$\\\\textrm{-}$', '$\\\\mathrm{One}$$\\\\textrm{-}$$\\\\mathrm{Two}$', '$\\\\mathrm{One}$ \\n $\\\\mathrm{Two}$', '$\\\\mathrm{One}$ \\n $\\\\mathrm{Two}$', '$\\\\mathrm{A}$ \\n $\\\\mathrm{}$$S_{Ti}$$\\\\mathrm{ \\n $\\\\mathrm{is \\n $\\\\mathrm{great}$ \\n $\\\\mathrm{but \\n $\\\\mathrm{use}$$\\\\textrm{-}$$\\\\mathrm{less}$']\n # print(str2tex(strin, space2linebreak=True, bold=True))\n # # ['$\\\\mathbf{One}$', '$\\\\mathbf{One}$$\\\\textbf{-}$', '$\\\\mathbf{One}$$\\\\textbf{-}$$\\\\mathbf{Two}$', '$\\\\mathbf{One}$ \\n $\\\\mathbf{Two}$', '$\\\\mathbf{One}$ \\n $\\\\mathbf{Two}$', '$\\\\mathbf{A}$ \\n $\\\\mathbf{}$$S_{Ti}$$\\\\mathbf{ \\n $\\\\mathbf{is \\n $\\\\mathbf{great}$ \\n $\\\\mathbf{but \\n $\\\\mathbf{use}$$\\\\textbf{-}$$\\\\mathbf{less}$']\n # print(str2tex(strin, usetex=False))\n # # ['One', 'One-', 'One-Two', 'One Two', 'One\\nTwo', 'A $S_{Ti}$ is great\\nbut use-less']\n # print(str2tex(strin, space2linebreak=True, usetex=False))\n # # ['One', 'One-', 'One-Two', 'One\\nTwo', 'One\\nTwo', 'A\\n$S_{Ti}$\\nis\\ngreat\\nbut\\nuse-less']\n", "#!/usr/bin/env python\nfrom __future__ import division, absolute_import, print_function\nimport numpy as np\nfrom jams.date2dec import date2dec\nfrom jams.const import cheat_quartz, cheat_water, cheat_air, density_quartz\nfrom scipy.interpolate import splrep, splint\nimport scipy.optimize as opt\n\ndef energyclosure(fluxfile, metfile, outdir, Rn, G, swdr, Ts=None, theta=None,\n depths=None, por=None, method='year', force0=True,\n delimiter=[',',','], skiprows=[1,1], format=['ascii','ascii'],\n undef=-9999, plot=False):\n '''\n Calculation of energy balance closure and correction of Eddy Covariance data\n with different methods. Possible calculation of soil heat flux from soil\n temperature and moisture if not given.\n \n \n Definition\n ----------\n energyclosure(fluxfile, metfile, outdir, Rn, G, swdr, Ts=None, theta=None,\n depths=None, por=None, method='year', force0=True,\n delimiter=[',',','], skiprows=[1,1], format=['ascii','ascii'],\n undef=-9999, plot=False):\n \n \n Input\n ----- \n fluxfile str, path and file name of fluxflag or fluxfill or fluxpart\n output file containing fluxes and flags\n metfile str, path and file name of the meteorology file (must be in\n sync with fluxfile)\n outdir str, path of the output folder\n Rn int, column number of net radiation [W m-2] in metfile, column\n number starts with 0 which is first data column.\n G int, column number of soil heat flux [W m-2] in metfile, column\n number starts with 0 which is first data column. If soil heat\n flux not available, set to False\n swdr int, column number of short wave downward radiation [W m-2] in\n metfile, column number starts with 0 which is first data column.\n swdr is used for swdr>0=isday\n \n\n Optional Input\n --------------\n Ts list(M) of int, if G is not given, column numbers of soil\n temperatures in certain depths in metfile, column number starts\n with 0 which is first data column.\n theta list(M) of int, if G is not given, column numbers of soil\n moistures in certain depths in metfile, column number starts\n with 0 which is first data column.\n depths list(M) or array(M) of int, if G is not given, depths of Ts and\n theta measurements [m], positively increasing with depths\n e.g. [0.05, 0.30, 0.60]\n por float, if G is not given, porosity of the soil [-], must be\n bigger or equal than np.amax(theta) \n method str, method of how energy balance closure is calculated and\n applied.\n if 'year', fit of whole year daytime flag=0 data\n Rn-G vs. H+Le and application of the fraction to all H, Le\n and E values\n implement new methods here\n implement new methods here\n implement new methods here\n (default: 'year')\n force0 bool, if method='year', True forces fit through origin, if False\n fit is allowed to have intercept (default: True)\n delimiter list of str, delimiters of fluxfile and metfile\n (default: [',',','])\n skiprows list of int, lines to skip at the beginning of fluxfile and\n metfile, e.g. header lines (default: [1,1])\n format list of str, time formats of fluxfile and metfile, 'ascii' and \n 'eng' possible (default: ['ascii','ascii'])\n undef int/float, missing value of fluxfile and metfile\n (default: -9999, np.nan is not possible)\n plot bool, if True performs plotting (default: False)\n \n \n Output\n ------\n fluxclosed.csv file containing fluxes and flags where depending on the\n method chosen fluxes are corrected for energy balance\n closure\n fluxclosed.pdf if method='year', plot of whole year daytime flag=0 data\n Rn-G vs. H+Le\n \n fluxclosed_stor.pdf if method='year', plot of whole year daytime flag=0 data\n Rn-G vs. H+Le including storages\n \n \n Restrictions\n ------------\n Works only with half hourly time steps\n\n\n License\n -------\n This file is part of the JAMS Python package, distributed under the MIT\n License. The JAMS Python package originates from the former UFZ Python library,\n Department of Computational Hydrosystems, Helmholtz Centre for Environmental\n Research - UFZ, Leipzig, Germany.\n\n Copyright (c) 2014 Arndt Piayda\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n\n History\n -------\n Written, AP, Sep 2014\n ''' \n ###########################################################################\n # reading input files\n d = np.loadtxt(fluxfile, dtype='|S100', delimiter=delimiter[0])\n m = np.loadtxt(metfile, dtype='|S100', delimiter=delimiter[1])\n \n assert (d.shape[1]==22) | (d.shape[1]==32), 'energyclosure: fluxfile must be from fluxpart and have 22 or 32 cols'\n \n if format[0]=='ascii':\n datev = date2dec(ascii=d[skiprows[0]:,0])\n elif format[0]=='eng':\n datev = date2dec(eng=d[skiprows[0]:,0])\n else:\n raise ValueError('energyclosure: unknown format') \n if format[1]=='ascii':\n datem = date2dec(ascii=m[skiprows[1]:,0])\n elif format[1]=='eng':\n datem = date2dec(eng=m[skiprows[1]:,0])\n else:\n raise ValueError('energyclosure: unknown format')\n \n val = np.where(d[skiprows[0]:,1:]=='', str(undef), d[skiprows[0]:,1:]).astype(np.float)\n met = np.where(m[skiprows[1]:,1:]=='', str(undef), m[skiprows[1]:,1:]).astype(np.float)\n \n ###########################################################################\n # assign variables\n if (d.shape[1]==22):\n H = val[:,0]\n Hflag = val[:,1]\n Le = val[:,3]\n Leflag = val[:,4]\n E = val[:,6]\n Eflag = val[:,7]\n else:\n H = val[:,0]\n Hflag = val[:,2]\n Le = val[:,4]\n Leflag = val[:,6]\n E = val[:,8]\n Eflag = val[:,10] \n H_stor = val[:,1]\n Hflag_stor = val[:,2]\n Le_stor = val[:,5]\n Leflag_stor = val[:,6]\n E_stor = val[:,9]\n Eflag_stor = val[:,10] \n Rn = met[:,Rn]\n Ts = met[:,Ts]\n swdr = met[:,swdr]\n isday = swdr>0.\n\n ###########################################################################\n # check if soil heat flux is given or needs to be calculated\n if not G:\n if Ts==None or theta==None or depths==None or por==None:\n raise ValueError('energyclosure: if G is not given, Ts, theta, depths and rhos are needed to calculate G')\n else:\n G=soilheatflux(Ts, theta, depths, rhos)\n else:\n G = met[:,G]\n \n ###########################################################################\n # apply energy balance closure methods\n # yearly approach\n if (method.lower() == 'year'):\n closure = energyclosure_year(H, Hflag, Le, Leflag, Rn, G, isday, outdir,\n force0=force0, undef=undef, plot='energyclosure.pdf')\n if force0:\n H_closed, Le_closed, E_closed = H/closure, Le/closure, E/closure\n else:\n H_closed, Le_closed, E_closed = H/closure[0], Le/closure[0], E/closure[0]\n\n if (d.shape[1]==32):\n closure_stor = energyclosure_year(H_stor, Hflag_stor, Le_stor, Leflag_stor,#\n Rn, G, isday, outdir, force0=force0,\n undef=undef, plot='energyclosure_stor.pdf')\n if force0:\n H_stor_closed, Le_stor_closed, E_stor_closed = H_stor/closure, Le_stor/closure, E_stor/closure\n else:\n H_stor_closed, Le_stor_closed, E_stor_closed = H_stor/closure[0], Le_stor/closure[0], E_stor/closure[0]\n \n # Include new methods here\n # Include new methods here\n # Include new methods here\n else:\n raise ValueError('energyclosure: method not implemented yet.')\n\n H_closed[H==undef] = undef\n Le_closed[Le==undef] = undef\n E_closed[E==undef] = undef\n if (d.shape[1]==32):\n H_stor_closed[H_stor==undef] = undef\n Le_stor_closed[Le_stor==undef] = undef\n E_stor_closed[E_stor==undef] = undef\n \n ###########################################################################\n # prepare and write output\n if (d.shape[1]==22): \n flux = np.vstack((H_closed,Le_closed,E_closed)).transpose()\n else:\n flux = np.vstack((H_closed,H_stor_closed,Le_closed,Le_stor_closed,E_closed,E_stor_closed)).transpose() \n \n flux_str = np.array([['%11.5f'%x for x in y] for y in flux])\n flux_str = np.where(flux_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), flux_str)\n \n if (d.shape[1]==22): \n d[skiprows[0]:,[1,4,7]] = flux_str\n else:\n d[skiprows[0]:,[1,2,5,6,9,10]] = flux_str\n \n np.savetxt('%s/fluxclosed.csv'%outdir, d, '%s', delimiter=',')\n\ndef soilheatflux(Ts, theta, depths, por, undef=-9999):\n '''\n Calculates soil heat flux from soil temperatures and soil moistures at\n different depths. It's best do include surface temperatures at 0 m.\n \n \n Definition\n ----------\n soilheatflux(Ts, theta, depths, por, undef=-9999):\n \n \n Input\n ----- \n Ts array(N,M), soil temperatures [K or degC]\n theta array(N,M), soil moisture [-]\n depths list(M) or array(M), depths of the Ts and theta measurements [m]\n positively increasing with depths e.g. [0.05, 0.30, 0.60]\n por float, porosity of the soil [-] must be bigger or equal\n than np.amax(theta)\n \n\n Optional Input\n --------------\n undef int/float, missing value of Ts and theta\n (default: -9999, np.nan is not possible)\n \n \n Output\n ------\n G array(N), soil heat flux [W m-2]\n \n \n Restrictions\n ------------\n Works only with half hourly time steps\n \n \n License\n -------\n This file is part of the JAMS Python package, distributed under the MIT\n License. The JAMS Python package originates from the former UFZ Python library,\n Department of Computational Hydrosystems, Helmholtz Centre for Environmental\n Research - UFZ, Leipzig, Germany.\n\n Copyright (c) 2014 Arndt Piayda\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n\n History\n -------\n Written, AP, Sep 2014\n ''' \n if (np.size(depths)!=Ts.shape[1]) or (Ts.shape!=theta.shape):\n raise ValueError('soilheatflux: dimensions mismatch')\n \n Ts = np.ma.array(Ts, mask=Ts==undef)\n theta = np.ma.array(theta, mask=theta==undef)\n \n # calc soil density and soil heat capacity\n rhos = (1.-por)*density_quartz\n csoil = cheat_quartz*(1.-por) + cheat_water*theta + cheat_air*(1-theta)*por\n \n # calculate heat flux \n T_diff = (Ts[:-1,:] - Ts[1:,:])/1800. * rhos * csoil[:-1,:]\n G = np.ma.masked_all_like(Ts[:,0])\n for i, item in enumerate(T_diff):\n if not item.mask.any():\n tck = splrep(depths, item, k=1)\n G[i+1] = splint(depths[0],depths[-1],tck)\n G[0]=G[1]\n \n return np.ma.filled(G, fill_value=undef)\n\ndef energyclosure_year(H, Hflag, Le, Leflag, Rn, G, isday, outdir, force0=True,\n undef=-9999, plot=False):\n '''\n Calculates energy balance closure with the 'year' approach. A straight line\n is fitted to Rn-g vs. H+Le and the fraction is returned.\n \n \n Definition\n ----------\n energyclosure_year(H, Le, Rn, G, isday, outdir, force0=force0, undef=undef,\n plot=plot):\n \n \n Input\n ----- \n H array(N), sensible heat flux [W m-2]\n Hflag array(N), quality flag of sensible heat flux, 0 where good quality\n Le array(N), latent heat flux [W m-2]\n Leflag array(N), quality flag of latent heat flux, 0 where good quality\n Rn array(N), net radiation [W m-2]\n G array(N), soil heat flux [W m-2]\n isday array(N), bool, True if day, False if night, fitting is done\n only to day data\n outdir str, path of the output folder\n \n\n Optional Input\n --------------\n force0 bool, if True fitting line is forced to origin and output is\n only the fraction, if False fitted line can have a intercept and\n output is then (fraction, intercept), (default: True)\n undef int/float, missing value of input (default: -9999, np.nan is\n not possible)\n plot bool, if False, no fitting plot is made and saved to outdir\n (default: False), otherwise give file name like 'energyclosure.pdf'\n \n \n Output\n ------\n fraction float, energy balance closure gap, e.g 0.8 means 80% of\n available energy is observed, 20% are missing. list(2) of floats\n with energy balance closure gap and intercept if force0=False\n \n \n License\n -------\n This file is part of the JAMS Python package, distributed under the MIT\n License. The JAMS Python package originates from the former UFZ Python library,\n Department of Computational Hydrosystems, Helmholtz Centre for Environmental\n Research - UFZ, Leipzig, Germany.\n\n Copyright (c) 2014 Arndt Piayda\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n\n History\n -------\n Written, AP, Sep 2014\n ''' \n ###########################################################################\n # variables\n H = np.ma.array(H, mask=(H==undef) | (~isday) |(Hflag>0))\n Le = np.ma.array(Le, mask=(Le==undef) | (~isday) |(Leflag>0))\n Rn = np.ma.array(Rn, mask=(Rn==undef) | (~isday))\n G = np.ma.array(G, mask=(G==undef) | (~isday))\n \n x = Rn-G\n y = H+Le\n \n ###########################################################################\n # fit\n if force0:\n p_guess = [1]\n func = lin2\n else:\n p_guess = [0,1]\n func = lin\n\n if plot:\n import matplotlib.pyplot as plt\n import matplotlib.backends.backend_pdf as pdf\n x_mod = np.arange(np.ma.min(x),np.ma.max(x),(np.ma.max(x)-np.ma.min(x))/50.)\n fig1=plt.figure('pre-fit')\n fig1.add_subplot(111, aspect='equal')\n plt.axhline(y=0, color='k')\n plt.axvline(x=0, color='k') \n plt.plot(x, y, 'bo', label='n: %i'%np.ma.count(x+y)) \n plt.plot(x_mod, func(x_mod,p_guess), 'r-')\n plt.xlabel('Rn-G')\n plt.ylabel('H+Le')\n plt.legend(loc='best')\n plt.show()\n \n p_opt = opt.fmin(absdif, p_guess, args=(x, y, func), disp=0)\n \n if plot:\n fig1=plt.figure('post-fit') \n fig1.add_subplot(111, aspect='equal')\n plt.axhline(y=0, color='k')\n plt.axvline(x=0, color='k') \n plt.plot(x, y, 'bo', label='n: %i'%np.ma.count(x+y)) \n if force0:\n plt.plot(x_mod, func(x_mod,p_opt), 'r-', label='slope: %0.2f'%p_opt)\n else:\n plt.plot(x_mod, func(x_mod,p_opt), 'r-', label='slope: %0.2f'%p_opt[0])\n plt.xlabel('Rn-G')\n plt.ylabel('H+Le')\n plt.legend(loc='best')\n plt.show()\n \n pp1 = pdf.PdfPages('%s/'%(outdir)+plot)\n fig1.savefig(pp1, format='pdf')\n pp1.close()\n\n return p_opt\n\ndef absdif(p,x,y,func):\n '''\n energyclosure: objective function\n '''\n return np.ma.sum(np.ma.abs(y-func(x, p)))\n\ndef lin(x, p):\n '''\n energyclosure: linear function\n ''' \n return p[0] * x + p[1]\n\ndef lin2(x, p):\n '''\n energyclosure: linear function with no intercept\n '''\n return p[0] * x\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n", "#!/usr/bin/env python\nfrom __future__ import division, absolute_import, print_function\nimport numpy as np\nimport os as os\nimport re\nimport shutil\nfrom time import localtime\nfrom scipy.stats import mode\n \ndef sltclean(indir, pat = '[a-zA-Z0-9]*.slt|[a-zA-Z0-9]*.SLT'):\n \"\"\" \n Moves *.slt files to a \"deleted\" folder to exclude them from further\n processing if they have a file size smaller than half of the regular\n file size. Regular file size is determined by mode(all file sizes in the\n folder). *.slt files are raw eddy covariance files (binary) recorded\n with EddyMeas (Kolle & Rebmann, 2007)\n \n \n Definition\n ----------\n sltclean(indir, pat = '[a-zA-Z0-9]*.slt|[a-zA-Z0-9]*.SLT'):\n \n \n Input\n ----- \n indir str, path of the folder containing the *.slt files \n \n \n Optional Input\n --------------\n pat str, regular expression, describing the name pattern of\n the *.slt files in the indir folder\n \n \n Output\n ------\n sltclean_X_X.log log file of the cleaning process\n \n \n License\n -------\n This file is part of the JAMS Python package, distributed under the MIT\n License. The JAMS Python package originates from the former UFZ Python library,\n Department of Computational Hydrosystems, Helmholtz Centre for Environmental\n Research - UFZ, Leipzig, Germany.\n\n Copyright (c) 2014 Arndt Piayda\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n \n \n History\n -------\n Written, AP, Jul 2014\n \n \"\"\"\n \n ###########################################################################\n # reading input directory\n dirlist = os.listdir(indir)\n sizelist, filelist = np.array([]), np.array([])\n if 'deleted' not in dirlist:\n os.mkdir('%s/deleted'%indir)\n \n ###########################################################################\n # remove all files and folders from list which are not *.slt files and get size\n pat = re.compile(pat)\n for item in dirlist:\n if re.search(pat, item):\n sizelist = np.append(sizelist, os.path.getsize('%s/%s' %(indir, item))/1000.)\n filelist = np.append(filelist, item)\n filesize = mode(sizelist)[0][0]\n \n ###########################################################################\n # move files to deleted which are too small and write log file\n delfiles = filelist[sizelist<filesize/2.]\n\n log = open('%s/deleted/sltclean%04i%02i%02i_%02i%02i%02i.log'\\\n %((indir,)+localtime()[:6]), 'w')\n log.write('Regular file size: %i\\n'%filesize)\n log.write('Moved to deleted:\\n')\n for item in delfiles:\n shutil.move('%s/%s'%(indir,item), '%s/deleted'%indir)\n log.write('%s\\n'%item)\n log.close()\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n", "#!/usr/bin/env python\n\"\"\"\nascii2ascii : Convert date notations between different regional variants\n such as English YYYY-MM-DD hh:mm:ss and US-English\n MM/DD/YYYY hh:mm:ss formats.\n\nThis module was written by Matthias Cuntz while at Department of\nComputational Hydrosystems, Helmholtz Centre for Environmental\nResearch - UFZ, Leipzig, Germany, and continued while at Institut\nNational de Recherche pour l'Agriculture, l'Alimentation et\nl'Environnement (INRAE), Nancy, France.\n\nCopyright (c) 2015-2020 Matthias Cuntz - mc (at) macu (dot) de\nReleased under the MIT License; see LICENSE file for details.\n\n* Written Feb 2015 by Matthias Cuntz (mc (at) macu (dot) de)\n* Removed usage of date2dec and dec2date, Nov 2016, Matthias Cuntz\n* Adapted docstrings to Python 2 and 3, Nov 2016, Matthias Cuntz\n* Added us and fr keywords, renamed eng to en, Mar 2018, Matthias Cuntz\n* Added two-digit year, Nov 2018, Matthias Cuntz\n* Removed bug from usage of en and old name eng, Jun 2019, Matthias Cuntz\n* Using numpy docstring format, May 2020, Matthias Cuntz\n\n.. moduleauthor:: Matthias Cuntz\n\nThe following functions are provided\n\n.. autosummary::\n ascii2ascii\n ascii2en\n ascii2fr\n ascii2us\n ascii2eng\n en2ascii\n fr2ascii\n us2ascii\n eng2ascii\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\nimport numpy as np\n\n\n__all__ = ['ascii2ascii',\n 'ascii2en', 'ascii2fr', 'ascii2us', 'ascii2eng',\n 'en2ascii', 'fr2ascii', 'us2ascii', 'eng2ascii']\n\n\ndef ascii2ascii(edate, full=False, en=False, fr=False, us=False, eng=False, YY=False):\n \"\"\"\n Convert date notations between ascii DD.MM.YYYY hh:mm:ss, English YYYY-MM-DD hh:mm:ss,\n American MM/DD/YYYY hh:mm:ss, and French DD/MM/YYYY hh:mm:ss.\n Input can only be ascii, English and American. Output can also be French DD/MM/YYYY hh:mm:ss.\n Use fr2ascii first for French input formats.\n\n Parameters\n ----------\n edate : array_like\n date strings in ascii, English or American format.\n full : bool, optional\n True: output dates arr all in full format DD.MM.YYYY hh:mm:ss; missing time inputs are 00 on output\n\n False: output dates are as long as input dates (default),\n e.g. [YYYY-MM-DD, YYYY-MM-DD hh:mm] gives [DD.MM.YYYY, DD.MM.YYYY hh:mm]\n en : bool, optional\n True: output format is English YYYY-MM-DD hh:mm:ss (default: False)\n fr : bool, optional\n True: output format is French DD/MM/YYYY hh:mm:ss (default: False)\n us : bool, optional\n True: output format is American MM/DD/YYYY hh:mm:ss (default: False)\n YY : bool, optional\n Year in input file is 2-digit year. Every year that is above the current year will\n be taken as being in 1900 (default: False).\n eng : bool, optional\n Same as en: obsolete.\n\n Returns\n -------\n date : array_like\n date strings in chosen date format.\n If no optional keyword True then output is in ascii format: DD.MM.YYYY hh:mm:ss.\n The output type will be the same as the type of the input.\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> print(\", \".join(ascii2ascii(edate)))\n 12.11.2014 12:00, 01.03.2015 17:56:00, 01.12.1990, 04.05.1786\n\n >>> print(\", \".join(ascii2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00, 04.05.1786 00:00:00\n\n >>> print(\", \".join(ascii2ascii(edate, en=True)))\n 2014-11-12 12:00, 2015-03-01 17:56:00, 1990-12-01, 1786-05-04\n\n >>> print(\", \".join(ascii2ascii(edate, en=True, full=True)))\n 2014-11-12 12:00:00, 2015-03-01 17:56:00, 1990-12-01 00:00:00, 1786-05-04 00:00:00\n\n >>> print(ascii2ascii(list(edate)))\n ['12.11.2014 12:00', '01.03.2015 17:56:00', '01.12.1990', '04.05.1786']\n\n >>> print(ascii2ascii(tuple(edate)))\n ('12.11.2014 12:00', '01.03.2015 17:56:00', '01.12.1990', '04.05.1786')\n\n >>> print(ascii2ascii(np.array(edate)))\n ['12.11.2014 12:00' '01.03.2015 17:56:00' '01.12.1990' '04.05.1786']\n\n >>> print(ascii2ascii(edate[0]))\n 12.11.2014 12:00\n\n >>> print(\", \".join(ascii2ascii(edate, us=True)))\n 11/12/2014 12:00, 03/01/2015 17:56:00, 12/01/1990, 05/04/1786\n\n >>> print(\", \".join(ascii2ascii(ascii2ascii(edate, en=True), us=True, full=True)))\n 11/12/2014 12:00:00, 03/01/2015 17:56:00, 12/01/1990 00:00:00, 05/04/1786 00:00:00\n\n >>> print(\", \".join(ascii2ascii(edate, fr=True)))\n 12/11/2014 12:00, 01/03/2015 17:56:00, 01/12/1990, 04/05/1786\n\n >>> print(\", \".join(ascii2ascii(edate, fr=True, full=True)))\n 12/11/2014 12:00:00, 01/03/2015 17:56:00, 01/12/1990 00:00:00, 04/05/1786 00:00:00\n\n # YY=True\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> print(\", \".join(ascii2ascii(edate, YY=True)))\n 12.11.2014 12:00, 01.03.2015 17:56:00, 01.12.1990\n >>> print(\", \".join(ascii2ascii(edate, en=True, YY=True)))\n 2014-11-12 12:00, 2015-03-01 17:56:00, 1990-12-01\n >>> print(\", \".join(ascii2ascii(edate, us=True, YY=True)))\n 11/12/2014 12:00, 03/01/2015 17:56:00, 12/01/1990\n >>> print(\", \".join(ascii2ascii(ascii2ascii(edate, en=True, YY=True), us=True, full=True)))\n 11/12/2014 12:00:00, 03/01/2015 17:56:00, 12/01/1990 00:00:00\n >>> print(\", \".join(ascii2ascii(edate, fr=True, full=True, YY=True)))\n 12/11/2014 12:00:00, 01/03/2015 17:56:00, 01/12/1990 00:00:00\n\n History\n -------\n Written, Matthias Cuntz, Feb 2015\n Modified, Matthias Cuntz, Sep 2015 - removed date2dec and dec2date\n Matthias Cuntz, Nov 2016 - adapted docstring to Python 2 and 3\n Matthias Cuntz, Mar 2018 - us, eng->en, fr\n Matthias Cuntz, Nov 2018 - YY\n Matthias Cuntz, Jun 2019 - eng->en working again\n Matthias Cuntz, May 2020 - numpy docstring format\n \"\"\"\n if eng: en = True\n assert (en+fr+us <= 1), 'en, fr and us keywords mutually exclusive.'\n\n # Input type and shape\n if isinstance(edate, list):\n idate = np.array(edate)\n elif isinstance(edate, tuple):\n idate = np.array(edate)\n elif isinstance(edate, np.ndarray):\n idate = edate.flatten()\n else:\n idate = np.array([edate])\n ndate = idate.size\n\n # Convert to given output type\n odate = list()\n if YY:\n import time as ptime\n iyr2 = int(ptime.asctime()[-2:])\n for i, d in enumerate(idate):\n if en:\n if '-' in d:\n if int(d[0:2]) > iyr2:\n dd = '19'+d # en -> en\n else:\n dd = '20'+d\n elif '/' in d:\n if int(d[6:8]) > iyr2:\n dd = '19'+d[6:8]+'-'+d[0:2]+'-'+d[3:5]+d[8:] # us -> en\n else:\n dd = '20'+d[6:8]+'-'+d[0:2]+'-'+d[3:5]+d[8:]\n else:\n if int(d[6:8]) > iyr2:\n dd = '19'+d[6:8]+'-'+d[3:5]+'-'+d[0:2]+d[8:] # ascii -> en\n else:\n dd = '20'+d[6:8]+'-'+d[3:5]+'-'+d[0:2]+d[8:]\n elif fr:\n if '-' in d:\n if int(d[0:2]) > iyr2:\n dd = d[6:8]+'/'+d[3:5]+'/19'+d[0:2]+d[8:] # en -> fr\n else:\n dd = d[6:8]+'/'+d[3:5]+'/20'+d[0:2]+d[8:]\n elif '/' in d:\n if int(d[6:8]) > iyr2:\n dd = d[3:5]+'/'+d[0:2]+'/19'+d[6:8]+d[8:] # us -> fr\n else:\n dd = d[3:5]+'/'+d[0:2]+'/20'+d[6:8]+d[8:]\n else:\n if int(d[6:8]) > iyr2:\n dd = d[0:2]+'/'+d[3:5]+'/19'+d[6:8]+d[8:] # ascii -> fr\n else:\n dd = d[0:2]+'/'+d[3:5]+'/20'+d[6:8]+d[8:]\n elif us:\n if '-' in d:\n if int(d[0:2]) > iyr2:\n dd = d[3:5]+'/'+d[6:8]+'/19'+d[0:2]+d[8:] # en -> us\n else:\n dd = d[3:5]+'/'+d[6:8]+'/20'+d[0:2]+d[8:]\n elif '/' in d:\n if int(d[6:8]) > iyr2:\n dd = d[0:6]+'19'+d[6:] # us -> us\n else:\n dd = d[0:6]+'20'+d[6:]\n else:\n if int(d[6:8]) > iyr2:\n dd = d[3:5]+'/'+d[0:2]+'/19'+d[6:8]+d[8:] # ascii -> us\n else:\n dd = d[3:5]+'/'+d[0:2]+'/20'+d[6:8]+d[8:]\n else:\n if '-' in d:\n if int(d[0:2]) > iyr2:\n dd = d[6:8]+'.'+d[3:5]+'.19'+d[0:2]+d[8:] # en -> ascii\n else:\n dd = d[6:8]+'.'+d[3:5]+'.20'+d[0:2]+d[8:]\n elif '/' in d:\n if int(d[6:8]) > iyr2:\n dd = d[3:5]+'.'+d[0:2]+'.19'+d[6:8]+d[8:] # us -> ascii\n else:\n dd = d[3:5]+'.'+d[0:2]+'.20'+d[6:8]+d[8:] # us -> ascii\n else:\n if int(d[6:8]) > iyr2:\n dd = d[0:6]+'19'+d[6:] # ascii -> ascii\n else:\n dd = d[0:6]+'20'+d[6:]\n odate.append(dd)\n else:\n for i, d in enumerate(idate):\n if en:\n if '-' in d:\n dd = d # en -> en\n elif '/' in d:\n dd = d[6:10]+'-'+d[0:2]+'-'+d[3:5]+d[10:] # us -> en\n else:\n dd = d[6:10]+'-'+d[3:5]+'-'+d[0:2]+d[10:] # ascii -> en\n elif fr:\n if '-' in d:\n dd = d[8:10]+'/'+d[5:7]+'/'+d[0:4]+d[10:] # en -> fr\n elif '/' in d:\n dd = d[3:5]+'/'+d[0:2]+'/'+d[6:10]+d[10:] # us -> fr\n else:\n dd = d[0:2]+'/'+d[3:5]+'/'+d[6:10]+d[10:] # ascii -> fr\n elif us:\n if '-' in d:\n dd = d[5:7]+'/'+d[8:10]+'/'+d[0:4]+d[10:] # en -> us\n elif '/' in d:\n dd = d # us -> us\n else:\n dd = d[3:5]+'/'+d[0:2]+'/'+d[6:10]+d[10:] # ascii -> us\n else:\n if '-' in d:\n dd = d[8:10]+'.'+d[5:7]+'.'+d[0:4]+d[10:] # en -> ascii\n elif '/' in d:\n dd = d[3:5]+'.'+d[0:2]+'.'+d[6:10]+d[10:] # us -> ascii\n else:\n dd = d # ascii -> ascii\n odate.append(dd)\n\n if full:\n odate = [ (d+' 00:00:00')[:19] if len(d) < 11 else (d+':00:00')[:19] for d in odate ]\n\n # Return right type\n if isinstance(edate, list):\n return odate\n elif isinstance(edate, tuple):\n return tuple(odate)\n elif isinstance(edate, np.ndarray):\n return np.array(odate).reshape(edate.shape)\n else:\n return odate[0]\n\n\ndef ascii2en(edate, **kwarg):\n \"\"\"\n Wrapper function for :func:`ascii2ascii` with English date format output, i.e. `en=True`:\n `ascii2ascii(edate, en=True, **kwarg)`\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> print(\", \".join(ascii2en(edate)))\n 2014-11-12 12:00, 2015-03-01 17:56:00, 1990-12-01, 1786-05-04\n\n >>> print(\", \".join(ascii2en(edate, full=True)))\n 2014-11-12 12:00:00, 2015-03-01 17:56:00, 1990-12-01 00:00:00, 1786-05-04 00:00:00\n\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> print(\", \".join(ascii2en(edate, full=True, YY=True)))\n 2014-11-12 12:00:00, 2015-03-01 17:56:00, 1990-12-01 00:00:00\n \"\"\"\n return ascii2ascii(edate, en=True, **kwarg)\n\n\ndef ascii2fr(edate, **kwarg):\n \"\"\"\n Wrapper function for :func:`ascii2ascii` with French date format output, i.e. `fr=True`:\n `ascii2ascii(edate, fr=True, **kwarg)`\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> print(\", \".join(ascii2fr(edate)))\n 12/11/2014 12:00, 01/03/2015 17:56:00, 01/12/1990, 04/05/1786\n\n >>> print(\", \".join(ascii2fr(edate, full=True)))\n 12/11/2014 12:00:00, 01/03/2015 17:56:00, 01/12/1990 00:00:00, 04/05/1786 00:00:00\n\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> print(\", \".join(ascii2fr(edate, full=True, YY=True)))\n 12/11/2014 12:00:00, 01/03/2015 17:56:00, 01/12/1990 00:00:00\n \"\"\"\n return ascii2ascii(edate, fr=True, **kwarg)\n\n\ndef ascii2us(edate, **kwarg):\n \"\"\"\n Wrapper function for :func:`ascii2ascii` with US-English date format output, i.e. `us=True`:\n `ascii2ascii(edate, us=True, **kwarg)`\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> print(\", \".join(ascii2ascii(edate, us=True)))\n 11/12/2014 12:00, 03/01/2015 17:56:00, 12/01/1990, 05/04/1786\n\n >>> print(\", \".join(ascii2ascii(ascii2ascii(edate, en=True), us=True, full=True)))\n 11/12/2014 12:00:00, 03/01/2015 17:56:00, 12/01/1990 00:00:00, 05/04/1786 00:00:00\n\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> print(\", \".join(ascii2ascii(ascii2ascii(edate, en=True, YY=True), us=True, full=True)))\n 11/12/2014 12:00:00, 03/01/2015 17:56:00, 12/01/1990 00:00:00\n \"\"\"\n return ascii2ascii(edate, us=True, **kwarg)\n\n\ndef ascii2eng(edate, **kwarg):\n \"\"\"\n Wrapper function for :func:`ascii2ascii` with English date format output, i.e. `en=True`:\n `ascii2ascii(edate, en=True, **kwarg)`\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> print(\", \".join(ascii2eng(edate)))\n 2014-11-12 12:00, 2015-03-01 17:56:00, 1990-12-01, 1786-05-04\n\n >>> print(\", \".join(ascii2eng(edate, full=True)))\n 2014-11-12 12:00:00, 2015-03-01 17:56:00, 1990-12-01 00:00:00, 1786-05-04 00:00:00\n\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> print(\", \".join(ascii2eng(edate, full=True, YY=True)))\n 2014-11-12 12:00:00, 2015-03-01 17:56:00, 1990-12-01 00:00:00\n \"\"\"\n return ascii2ascii(edate, en=True, **kwarg)\n\n\ndef en2ascii(edate, **kwarg):\n \"\"\"\n Wrapper function for ascii2ascii with ascii date format output (default):\n `ascii2ascii(edate, **kwarg)`\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> edate = ascii2ascii(edate, en=True)\n >>> print(\", \".join(en2ascii(edate)))\n 12.11.2014 12:00, 01.03.2015 17:56:00, 01.12.1990, 04.05.1786\n\n >>> print(\", \".join(en2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00, 04.05.1786 00:00:00\n\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> edate = ascii2ascii(edate, en=True, YY=True)\n >>> print(\", \".join(en2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00\n \"\"\"\n return ascii2ascii(edate, **kwarg)\n\n\ndef fr2ascii(edate, full=False, YY=False):\n \"\"\"\n Convert French date notation DD/MM/YYYY hh:mm:ss to ascii notation DD.MM.YYYY hh:mm:ss.\n Simply replaces '/' with '.', assuring iterable type.\n\n\n Parameters\n ----------\n edate : array_like\n date strings in French date format DD/MM/YYYY [hh:mm:ss]\n full : bool, optional\n True: output dates arr all in full format DD.MM.YYYY hh:mm:ss; missing time inputs are 00 on output\n\n False: output dates are as long as input dates (default),\n e.g. [DD/MM/YYYY, DD/MM/YYYY hh:mm] gives [DD.MM.YYYY, DD.MM.YYYY hh:mm]\n YY : bool, optional\n Year in input file is 2-digit year. Every year that is above the current year will\n be taken as being in 1900 (default: False).\n\n Returns\n -------\n date : array_like\n date strings in ascii date format: DD.MM.YYYY hh:mm:ss.\n The output type will be the same as the type of the input.\n\n Examples\n --------\n >>> edate = ['12/11/2014 12:00', '01/03/2015 17:56:00', '01/12/1990', '04/05/1786']\n >>> print(\", \".join(fr2ascii(edate)))\n 12.11.2014 12:00, 01.03.2015 17:56:00, 01.12.1990, 04.05.1786\n\n >>> print(\", \".join(fr2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00, 04.05.1786 00:00:00\n\n >>> print(fr2ascii(list(edate)))\n ['12.11.2014 12:00', '01.03.2015 17:56:00', '01.12.1990', '04.05.1786']\n\n >>> print(fr2ascii(tuple(edate)))\n ('12.11.2014 12:00', '01.03.2015 17:56:00', '01.12.1990', '04.05.1786')\n\n >>> print(fr2ascii(np.array(edate)))\n ['12.11.2014 12:00' '01.03.2015 17:56:00' '01.12.1990' '04.05.1786']\n\n >>> print(fr2ascii(edate[0]))\n 12.11.2014 12:00\n\n # YY=True\n >>> edate = ['12/11/14 12:00', '01/03/15 17:56:00', '01/12/90']\n >>> print(\", \".join(fr2ascii(edate, YY=True)))\n 12.11.2014 12:00, 01.03.2015 17:56:00, 01.12.1990\n\n >>> print(\", \".join(fr2ascii(edate, full=True, YY=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00\n\n History\n -------\n Written, Matthias Cuntz, Mar 2018\n Modified, Matthias Cuntz, Nov 2018 - YY\n Matthias Cuntz, May 2020 - numpy docstring format\n \"\"\"\n\n # Input type and shape\n if isinstance(edate, list):\n idate = edate\n elif isinstance(edate, tuple):\n idate = list(edate)\n elif isinstance(edate, np.ndarray):\n idate = list(edate.flatten())\n else:\n idate = [edate]\n odate = [ d.replace('/','.') for d in idate ]\n\n if YY:\n import time as ptime\n iyr2 = int(ptime.asctime()[-2:])\n odate = [ d[0:6]+'19'+d[6:] if int(d[6:8]) > iyr2 else d[0:6]+'20'+d[6:] for d in odate ] # ascii -> ascii\n\n if full:\n odate = [ (d+' 00:00:00')[:19] if len(d) < 11 else (d+':00:00')[:19] for d in odate ]\n\n # Return right type\n if isinstance(edate, list):\n return odate\n elif isinstance(edate, tuple):\n return tuple(odate)\n elif isinstance(edate, np.ndarray):\n return np.array(odate).reshape(edate.shape)\n else:\n return odate[0]\n\n\ndef us2ascii(edate, **kwarg):\n \"\"\"\n Wrapper function for :func:`ascii2ascii` with ascii date format output (default):\n `ascii2ascii(edate, **kwarg)`\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> edate = ascii2ascii(edate, us=True)\n >>> print(\", \".join(us2ascii(edate)))\n 12.11.2014 12:00, 01.03.2015 17:56:00, 01.12.1990, 04.05.1786\n\n >>> print(\", \".join(us2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00, 04.05.1786 00:00:00\n\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> edate = ascii2ascii(edate, us=True, YY=True)\n >>> print(\", \".join(us2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00\n \"\"\"\n return ascii2ascii(edate, **kwarg)\n\n\ndef eng2ascii(edate, **kwarg):\n \"\"\"\n Wrapper function for :func:`ascii2ascii` with ascii date format output (default):\n `ascii2ascii(edate, **kwarg)`\n\n Examples\n --------\n >>> edate = ['2014-11-12 12:00', '01.03.2015 17:56:00', '1990-12-01', '04.05.1786']\n >>> edate = ascii2ascii(edate, en=True)\n >>> print(\", \".join(eng2ascii(edate)))\n 12.11.2014 12:00, 01.03.2015 17:56:00, 01.12.1990, 04.05.1786\n\n >>> print(\", \".join(eng2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00, 04.05.1786 00:00:00\n\n >>> edate = ['14-11-12 12:00', '01.03.15 17:56:00', '90-12-01']\n >>> edate = ascii2ascii(edate, en=True, YY=True)\n >>> print(\", \".join(eng2ascii(edate, full=True)))\n 12.11.2014 12:00:00, 01.03.2015 17:56:00, 01.12.1990 00:00:00\n \"\"\"\n return ascii2ascii(edate, **kwarg)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)\n", "#!/usr/bin/env python\nfrom __future__ import division, absolute_import, print_function\nimport numpy as np\nfrom jams.date2dec import date2dec\nfrom jams.const import mmol_co2, mmol_h2o, mmol_air, cheat_air, latentheat_vaporization, T0\nfrom scipy.interpolate import splrep, splint\nfrom jams.esat import esat\n\ndef profile2storage(fluxfile, fluxfile2, profilefile, outdir, heights, CO2=None,\n H2O=None, T=None, rH=None, delimiter=[',',',',','],\n skiprows=[1,1,1], format=['ascii','ascii','ascii'],\n undef=-9999, plot=False):\n '''\n Calculates storage fluxes for changes in CO2, H2O, air temperature and air\n moisture from profile data or meteorological data to correct Eddy\n Covariance fluxes. FLux files from EddySoft and from fluxflag are needed as\n well as a file with the profile or meteo data. Fluxes will be updated with\n the respective storage fluxes and saved in a new file. Multiple application\n of this routine with different profile or meteo files are possible to\n correct e.g. the CO2, H2O and latent heat fluxes with profile data of CO2\n and H2O concentrations and afterwards the H flux with temperature data from\n another file.\n \n \n Definition\n ----------\n profile2storage(fluxfile, fluxfile2, profilefile, outdir, heights, CO2=None,\n H2O=None, T=None, rH=None, delimiter=[',',',',','],\n skiprows=[1,1,1], format=['ascii','ascii','ascii'],\n undef=-9999, plot=False):\n \n \n Input\n ----- \n fluxfile str, path and file name of fluxflag output file containing\n fluxes and flags. These fluxes will be updated by the storage\n fluxes and saved as a new file\n fluxfile2 str, path and file name of EddyFlux output file (timestep\n checked) containing original fluxes\n profilefile str, path and file name of the profile file or meteorology file\n containing CO2, H2O, T or rH values to compute the profile\n storage from\n outdir str, path of the output folder\n heights list of floats, observation heights of the profile [m],\n increasing e.g. [0.5,1.0,10.0,20.0].\n CO2 list of int, column numbers of CO2 concentrations for the\n different heights (in the same order) [mumol/mol] in profilefile,\n column number starts with 0 which is first data column.\n H2O list of int, column numbers of H2O concentrations for the\n different heights (in the same order) [mmol/mol] in profilefile,\n column number starts with 0 which is first data column.\n T list of int, column numbers of air temperatures for the\n different heights (in the same order) [degC] in profilefile,\n column number starts with 0 which is first data column.\n rH list of int, column numbers of relative humidity for the\n different heights (in the same order) [%] in profilefile,\n column number starts with 0 which is first data column. The\n calculation of air vapour energy storage change within the\n profile works only when T is given as well.\n \n\n Optional Input\n --------------\n delimiter list of str, delimiters of fluxfile, fluxfile and profilefile\n (default: [',',',',','])\n skiprows list of int, lines to skip at the beginning of fluxfile,\n fluxfile and profilefile, e.g. header lines (default: [1,1,1])\n format list of str, time formats of fluxfile, fluxfile and profilefile,\n 'ascii' and 'eng' possible (default: ['ascii','ascii','ascii'])\n undef int/float, missing value of fluxfile, fluxfile and profilefile\n (default: -9999, np.nan is not possible)\n plot bool, if True performs plotting (default: False)\n \n \n Output\n ------\n flux+stor.csv file containing fluxes and flags where storage fluxes are\n added in an additional column and storage fluxes are appended\n to the end of the file\n \n \n Restrictions\n ------------\n Works only with half hourly time steps, all files in sync\n\n\n License\n -------\n This file is part of the JAMS Python package, distributed under the MIT\n License. The JAMS Python package originates from the former UFZ Python library,\n Department of Computational Hydrosystems, Helmholtz Centre for Environmental\n Research - UFZ, Leipzig, Germany.\n\n Copyright (c) 2014 Arndt Piayda\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n\n History\n -------\n Written, AP, Sep 2014\n '''\n ###########################################################################\n # time interval\n int = 30.\n dt = int*60.\n \n if plot:\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n import matplotlib.backends.backend_pdf as pdf\n \n ###########################################################################\n # reading input files\n # fluxes to correct for storage changes\n d1 = np.loadtxt(fluxfile, dtype='|S100', delimiter=delimiter[0])\n # original flux file from EddyFlux containing air density rho_a\n d2 = np.loadtxt(fluxfile2, dtype='|S100', delimiter=delimiter[1])\n # file containing profile data (can be meteo file if no profile available)\n d3 = np.loadtxt(profilefile, dtype='|S100', delimiter=delimiter[2])\n \n assert (d1.shape[1]==11) | (d1.shape[1]==19), 'profile2storage: fluxfile must be from fluxflag or profiletostorage and have 11 or 19 cols'\n assert d2.shape[1]==68, 'profile2storage: fluxfile2 must be from EddyFlux and have 68 cols'\n assert d1.shape[0]==d2.shape[0], 'profile2storage: fluxfile and fluxfile2 must be in sync'\n assert d1.shape[0]==d3.shape[0], 'profile2storage: fluxfile and profilefile must be in sync'\n assert (((H2O==None) & (rH==None)) ^ ((H2O!=None) ^ (rH!=None))), 'profile2storage: give either H2O or rH, both would be double correction'\n \n if format[0]=='ascii':\n datev = date2dec(ascii=d1[skiprows[0]:,0])\n elif format[0]=='eng':\n datev = date2dec(eng=d1[skiprows[0]:,0])\n else:\n raise ValueError('profile2storage: unknown format') \n if format[2]=='ascii':\n datem = date2dec(ascii=d2[skiprows[2]:,0])\n elif format[2]=='eng':\n datem = date2dec(eng=d2[skiprows[2]:,0])\n else:\n raise ValueError('profile2storage: unknown format')\n \n flux1 = np.where(d1[skiprows[0]:,1:]=='', str(undef), d1[skiprows[0]:,1:]).astype(np.float)\n flux2 = np.where(d2[skiprows[1]:,1:]=='', str(undef), d2[skiprows[1]:,1:]).astype(np.float)\n prof = np.where(d3[skiprows[2]:,1:]=='', str(undef), d3[skiprows[2]:,1:]).astype(np.float)\n \n flux1 = np.ma.array(flux1, mask=flux1==undef, hard_mask=True)\n flux2 = np.ma.array(flux2, mask=flux2==undef)\n prof = np.ma.array(prof, mask=prof==undef)\n \n ###########################################################################\n # assign variables\n if d1.shape[1]==11:\n H, Hflag = flux1[:,0], flux1[:,1]\n Le, Leflag = flux1[:,2], flux1[:,3]\n E, Eflag = flux1[:,4], flux1[:,5]\n C, Cflag = flux1[:,6], flux1[:,7]\n else:\n H, Hflag = flux1[:,0], flux1[:,2]\n Le, Leflag = flux1[:,3], flux1[:,5]\n E, Eflag = flux1[:,6], flux1[:,8]\n C, Cflag = flux1[:,9], flux1[:,11]\n p = flux2[:,58] # [hPa]\n rho = flux2[:,62] # [kg/m3]\n \n ###########################################################################\n # prepare output array\n d4 = np.copy(d1)\n if d1.shape[1]==11:\n temp = np.empty((d1.shape[0],4), dtype='|S100')\n temp[:] = ' '*(11-len(str(undef)))+str(undef)\n temp[0,:] = [' H+sT',' LE+sLE',' E+sE',' C+sC']\n d4 = np.insert(d4, [2,4,6,8], temp, axis=1)\n \n temp[0,:] = [' sT',' sLE',' sE',' sC']\n d4 = np.append(d4, temp, axis=1)\n \n ###########################################################################\n # calls\n if CO2:\n CO2 = prof[:,CO2]\n assert CO2.shape[1]==len(heights), 'profile2storage: number of CO2 cols must equal heights'\n # calculate storage flux and storage flux flag\n sfCO2 = stor2flux(CO2, rho, heights, dt, 'CO2')\n sfCO2flag = sfCO2.mask.astype(np.int)\n # add to eddy flux\n newC = C + np.ma.filled(sfCO2, 0)\n # format and write into output array\n newC_str = np.array(['%11.5f'%x for x in np.ma.filled(newC, undef)])\n newC_str = np.where(newC_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), newC_str)\n sfCO2_str = np.array(['%11.5f'%x for x in np.ma.filled(sfCO2, undef)])\n sfCO2_str = np.where(sfCO2_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), sfCO2_str)\n d4[skiprows[0]:,11] = newC_str\n d4[skiprows[0]:,18] = sfCO2_str\n\n if plot:\n storplot(CO2, datev, heights, C, sfCO2, newC, 'storageCO2.pdf', pdf, plt, mpl, outdir)\n \n if H2O:\n H2O = prof[:,H2O]\n assert H2O.shape[1]==len(heights), 'profile2storage: number of H2O cols must equal heights'\n # calculate storage flux and storage flux flag\n sfH2O = stor2flux(H2O, rho, heights, dt, 'H2O')\n sfH2O_Wm2 = sfH2O * mmol_h2o * latentheat_vaporization /1.e6\n sfH2Oflag = sfH2O.mask.astype(np.int)\n # add to eddy flux\n newE = E + np.ma.filled(sfH2O, 0)\n newLe = Le + np.ma.filled(sfH2O_Wm2, 0)\n # format and write into output array\n newE_str = np.array(['%11.5f'%x for x in np.ma.filled(newE, undef)])\n newLe_str = np.array(['%11.5f'%x for x in np.ma.filled(newLe, undef)])\n sfH2O_str = np.array(['%11.5f'%x for x in np.ma.filled(sfH2O, undef)])\n sfH2O_Wm2_str = np.array(['%11.5f'%x for x in np.ma.filled(sfH2O_Wm2, undef)])\n newE_str = np.where(newE_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), newE_str)\n newLe_str = np.where(newLe_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), newLe_str)\n sfH2O_str = np.where(sfH2O_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), sfH2O_str)\n sfH2O_Wm2_str = np.where(sfH2O_Wm2_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), sfH2O_Wm2_str)\n d4[skiprows[0]:,8] = newE_str\n d4[skiprows[0]:,17] = sfH2O_str\n d4[skiprows[0]:,5] = newLe_str\n d4[skiprows[0]:,16] = sfH2O_Wm2_str\n\n if plot:\n storplot(H2O, datev, heights, E, sfH2O, newE, 'storageH2O.pdf', pdf, plt, mpl, outdir)\n\n if T:\n T = prof[:,T]\n assert T.shape[1]==len(heights), 'profile2storage: number of T cols must equal heights'\n # calculate storage flux and storage flux flag\n sfT = stor2flux(T, rho, heights, dt, 'T')\n sfTflag = sfT.mask.astype(np.int)\n # add to eddy flux\n newH = H + np.ma.filled(sfT, 0)\n # format and write into output array\n newH_str = np.array(['%11.5f'%x for x in np.ma.filled(newH, undef)])\n newH_str = np.where(newH_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), newH_str)\n sfT_str = np.array(['%11.5f'%x for x in np.ma.filled(sfT, undef)])\n sfT_str = np.where(sfT_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), sfT_str)\n d4[skiprows[0]:,2] = newH_str\n d4[skiprows[0]:,15] = sfT_str\n\n if plot:\n storplot(T, datev, heights, H, sfT, newH, 'storageT.pdf', pdf, plt, mpl, outdir)\n \n if rH:\n rH = prof[:,rH]\n assert rH.shape[1]==len(heights), 'profile2storage: number of rH cols must equal heights'\n # calculate specific humidity\n vapourpressure = esat(T+T0)*(rH/100.)/100. #[hPa]\n specifichumidity = (mmol_h2o/mmol_air*vapourpressure) / (p-(1.-mmol_h2o/mmol_air)*vapourpressure)\n # calculate storage flux and storage flux flag\n sfrH_Wm2 = stor2flux(specifichumidity, rho, heights, dt, 'rH')\n sfrH = sfrH_Wm2 * 1.e6 / (mmol_h2o * latentheat_vaporization)\n sfrHflag = sfrH.mask.astype(np.int)\n # add to eddy flux\n newE = E + np.ma.filled(sfrH, 0)\n newLe = Le + np.ma.filled(sfrH_Wm2, 0)\n # format and write into output array\n newE_str = np.array(['%11.5f'%x for x in np.ma.filled(newE, undef)])\n newLe_str = np.array(['%11.5f'%x for x in np.ma.filled(newLe, undef)])\n sfrH_str = np.array(['%11.5f'%x for x in np.ma.filled(sfrH, undef)])\n sfrH_Wm2_str = np.array(['%11.5f'%x for x in np.ma.filled(sfrH_Wm2, undef)])\n newE_str = np.where(newE_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), newE_str)\n newLe_str = np.where(newLe_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), newLe_str)\n sfrH_str = np.where(sfrH_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), sfrH_str)\n sfrH_Wm2_str = np.where(sfrH_Wm2_str=='%11.5f'%undef, ' '*(11-len(str(undef)))+str(undef), sfrH_Wm2_str)\n d4[skiprows[0]:,8] = newE_str\n d4[skiprows[0]:,17] = sfrH_str\n d4[skiprows[0]:,5] = newLe_str\n d4[skiprows[0]:,16] = sfrH_Wm2_str\n \n if plot:\n storplot(rH, datev, heights, E, sfH2O, newE, 'storagerH.pdf', pdf, plt, mpl, outdir)\n \n ###########################################################################\n # write output\n np.savetxt('%s/flux+stor.csv'%outdir, d4, '%s', delimiter=',')\n\ndef stor2flux(concentrations, rho, heights, dt, constituent='CO2'):\n '''\n '''\n xb = 0.0 # bottom height of interpolation\n xe = np.amax(heights) # top height of interpolation\n \n if constituent=='CO2':\n # mole volume [m3/mol] = mmol_co2[g/mol]/(rho[kg/m3]*1000.)\n m = mmol_co2/(rho*1000.)\n elif constituent=='H2O':\n # mole volume [m3/mol] = mmol_h2o[g/mol]/(rho[kg/m3]*1000.)\n m = mmol_h2o/(rho*1000.)\n elif constituent=='T':\n # 1/energy content of the air [1/(J/m3 K)] = 1/ (rho[kg/m3]*heat capacity of air [J/kg K])\n m = 1./(rho*cheat_air)\n elif constituent=='rH':\n # 1/energy content of vapor [1/(J/m3)] = 1/ (rho[kg/m3] * specific heat of vaporization of water [J/kg])\n m = 1./(rho * latentheat_vaporization)\n else:\n raise ValueError('stor2flux: unknown constituent')\n \n ###########################################################################\n # calculate storage for every time step\n storage, sf = np.ma.masked_all_like(rho), np.ma.masked_all_like(rho)\n for i,item in enumerate(concentrations):\n if not item.mask.any():\n # if only one height given, take box approach (splrep does not work)\n if len(heights)==1:\n storage[i] = item*heights\n # else interpolate nicely :-)\n else:\n tck = splrep(heights,item,xb=xb,xe=xe,k=1)\n storage[i] = splint(xb,xe,tck)\n \n ###########################################################################\n # calculate storage flux\n # storage flux per time step\n # for CO2: [mumol/m*2] = [mumol/mol*m]/[m3/mol]\n # for H2O: [mmol/m*2] = [mmol/mol*m]/[m3/mol]\n # for T: [J/m*2] = [K*m]/[1/(J/m3 K)]\n # for rH: [J/m*2] = [m]/[1/(J/m3)]\n sf[1:] = storage[:-1]/m[:-1] - storage[1:]/m[1:]\n sf[0] = sf[1]\n # storage flux per second\n # for CO2: [mumol/(m2*s)]\n # for H2O: [mmol/(m2*s)]\n # for T: [J/(m2*s)]=[W/m*2]\n # for rH: [J/(m2*s)]=[W/m*2]\n sf = sf/dt\n \n return sf\n\ndef storplot(conc, date, heights, oriflux, storflux, newflux, name, pdf, plt, mpl, outdir):\n '''\n '''\n majticks = mpl.dates.MonthLocator(bymonthday=1)\n format_str='%d %m %Y %H:%M'\n date01 = date2dec(yr=1, mo=1, dy=2, hr=0, mi=0, sc=0)\n \n conc = np.ma.copy(conc.transpose())\n date = np.ma.copy(date-date01)\n \n pp1 = pdf.PdfPages(outdir+'/'+name)\n fig1 = plt.figure(name)\n sub1 = fig1.add_subplot(211)\n for i, item in enumerate(conc):\n sub1.plot(date, item, label='%2.1f m'%(heights[i]))\n plt.legend(loc='best')\n \n sub2 = fig1.add_subplot(212)\n sub2.axhline(y=0, xmin=0, xmax=1, color='k')\n sub2.plot(date, oriflux, 'b-', label='original')\n sub2.plot(date, storflux, 'r-', label='storage')\n sub2.plot(date, newflux, 'g-', label='new')\n plt.legend(loc='best')\n \n sub1.set_xlim(date[0],date[-1])\n sub1.xaxis.set_major_locator(majticks)\n sub1.xaxis.set_major_formatter(mpl.dates.DateFormatter(format_str))\n sub2.set_xlim(date[0],date[-1])\n sub2.xaxis.set_major_locator(majticks)\n sub2.xaxis.set_major_formatter(mpl.dates.DateFormatter(format_str))\n fig1.autofmt_xdate()\n \n plt.show()\n fig1.savefig(pp1, format='pdf')\n pp1.close()\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n" ]
[ [ "numpy.sqrt", "numpy.isnan", "numpy.ma.abs", "numpy.std", "numpy.mean", "numpy.ma.array", "numpy.corrcoef" ], [ "numpy.array" ], [ "matplotlib.pyplot.legend", "numpy.vstack", "numpy.ma.count", "scipy.optimize.fmin", "numpy.ma.array", "numpy.ma.max", "matplotlib.backends.backend_pdf.PdfPages", "numpy.ma.min", "numpy.size", "matplotlib.pyplot.figure", "numpy.savetxt", "matplotlib.pyplot.show", "numpy.array", "matplotlib.pyplot.ylabel", "scipy.interpolate.splrep", "numpy.ma.filled", "matplotlib.pyplot.axhline", "matplotlib.pyplot.axvline", "scipy.interpolate.splint", "numpy.ma.masked_all_like", "matplotlib.pyplot.xlabel", "numpy.loadtxt" ], [ "numpy.append", "numpy.array", "scipy.stats.mode" ], [ "numpy.array" ], [ "matplotlib.pyplot.legend", "numpy.amax", "numpy.ma.array", "matplotlib.backends.backend_pdf.PdfPages", "numpy.copy", "numpy.insert", "matplotlib.dates.MonthLocator", "matplotlib.pyplot.figure", "matplotlib.dates.DateFormatter", "numpy.append", "numpy.loadtxt", "numpy.savetxt", "matplotlib.pyplot.show", "scipy.interpolate.splrep", "numpy.ma.filled", "numpy.ma.copy", "scipy.interpolate.splint", "numpy.ma.masked_all_like", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] } ]
Davide-DD/distributed-machine-learning-architectures
[ "998d86368c4122ad9937b505405191b316afb060", "998d86368c4122ad9937b505405191b316afb060" ]
[ "architectures/gossip-learning/nodes/fog-node/code/classes/aged_model.py", "analyzer/federated_visualize.py" ]
[ "from keras import backend as K\nfrom keras.models import *\nfrom keras.layers import *\nimport os\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\n\n\nclass AgedModel:\n\n\n\tdef __init__(self, model=None, age=None):\t\t\n\t\tself.graph = tf.Graph()\n\n\t\twith self.graph.as_default():\n\n\t\t\tself.session = tf.Session()\n\n\t\t\twith self.session.as_default():\n\n\t\t\t\tif model == None:\n\t\t\t\t\tn_sensors, t_periods = 4, 60\n\n\t\t\t\t\t# L'oggetto Sequential crea una pila lineare di livelli\n\t\t\t\t\tmodel = Sequential()\n\n\t\t\t\t\t# Come primo livello, aggiunge un livello di convoluzione a 1 dimensione con i seguenti argomenti: \n\t\t\t\t\t# 1. Filters: specifica il numero di filtri che vogliamo applicare (= larghezza dell'output)\n\t\t\t\t\t# 2. Kernel_size: specifica quanti dati vengono convoluti contemporaneamente (se si sottrae alla lunghezza dell'input e si aggiunge 1 si ha la lunghezza dell'output)\n\t\t\t\t\t# 3. activation: funzione di attivazione dei neuroni\n\t\t\t\t\t# 4. input_shape: definisce la \"forma\" dell'input\n\t\t\t\t\tmodel.add(Conv1D(100, 6, activation='relu', input_shape=(t_periods, n_sensors)))\n\n\t\t\t\t\t# Altro livello come sopra\n\t\t\t\t\tmodel.add(Conv1D(100, 6, activation='relu'))\n\n\t\t\t\t\t# Livello di pooling per convoluzioni 1D: prende 3 input alla volta e li sostituisce con il valore massimo che trova per evitare l'overfitting\n\t\t\t\t\tmodel.add(MaxPooling1D(3))\n\n\t\t\t\t\t# Altro livello di convoluzione 1D\n\t\t\t\t\tmodel.add(Conv1D(160, 6, activation='relu'))\n\n\t\t\t\t\t# Ultimo livello di convoluzione 1D\n\t\t\t\t\tmodel.add(Conv1D(160, 6, activation='relu'))\n\n\t\t\t\t\t# Livello di pooling che computa il valore medio per ogni riga\n\t\t\t\t\tmodel.add(GlobalAveragePooling1D())\n\n\t\t\t\t\t# Non proprio un livello: serve a settare a 0 la metà (0.5) dei valori in input per ridurre l'overfitting\n\t\t\t\t\tmodel.add(Dropout(0.5))\n\n\t\t\t\t\t# Ultimo livello composto da 3 nodi con attivazione softmax, che:\n\t\t\t\t\t# Assegna a ogni valore in uscita dai nodi sopra un valore compreso tra 0 e 1; la somma di questi valori fa 1\n\t\t\t\t\tmodel.add(Dense(3, activation='softmax'))\n\n\t\t\t\t\t# Specifica come si esegue il processo di apprendimento dai dati, utilizzando:\n\t\t\t\t\t# 1. loss: funzione che si cerca di minimizzare\n\t\t\t\t\t# 2. optimizer: funzione che si utilizza per cambiare i pesi (adam è un miglioramento di SGD)\n\t\t\t\t\t# 3. metrics: lista di metriche che vuoi tenere sott'occhio durante l'apprendimento\n\t\t\t\t\tmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n\t\t\t\t\tself.model = model\n\n\t\t\t\telse:\n\t\t\t\t\tself.model = load_model(model)\n\n\t\tif age != None:\n\t\t\tself.age = age\n\t\telse:\n\t\t\tself.age = datetime.timestamp(datetime.now())\n\n\n\tdef train(self,data):\n\t\twith self.graph.as_default():\n\t\t\twith self.session.as_default():\n\t\t\t\tx_train, y_train = data\n\t\t\t\t# Addestra il modello, restituendo infine un oggetto History con vari parametri che permettono di vedere come si sono evolute le performance\n\t\t\t\t# 1. numpy array o lista di numpy array (secondo la dimensionalità attesa)\n\t\t\t\t# 2. come sopra\n\t\t\t\t# 3. numero di sample da utilizzare prima di aggiornare i pesi\n\t\t\t\t# 4. numero di iterazioni da fare sui dati in input\n\t\t\t\t# 5. frazione dei dati di apprendimento da utilizzare come validazione\n\t\t\t\tself.model.fit(x_train, y_train, batch_size=3, epochs=5, verbose=1)\n\n\n\tdef test(self, data):\n\t\twith self.graph.as_default():\n\t\t\twith self.session.as_default():\n\t\t\t\tx_test, y_test = data\n\n\t\t\t\treturn self.model.evaluate(x_test, y_test, verbose=1)\n\t\t\n\n\tdef predict(self,data):\n\t\twith self.graph.as_default():\n\t\t\twith self.session.as_default():\n\t\t\t\treturn self.model.predict(data)\n\n\n\tdef get_weights(self):\n\t\twith self.graph.as_default():\n\t\t\twith self.session.as_default():\t\n\t\t\t\treturn self.model.get_weights()\n\n\n\tdef set_weights(self, weights):\t\n\t\twith self.graph.as_default():\n\t\t\twith self.session.as_default():\t\n\t\t\t\treturn self.model.set_weights(weights)\n\n\n\tdef export(self):\n\t\twith self.graph.as_default():\n\t\t\twith self.session.as_default():\t\n\t\t\t\tfile_name = 'my_model' + str(datetime.timestamp(datetime.now())) + '.h5'\n\t\t\t\tfile_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), file_name)\n\t\t\t\tfile = open(file_path, 'wb+')\n\t\t\t\tself.model.save(file_path)\n\t\t\t\tfile.close()\n\t\t\t\treturn open(file_path, 'rb'), file_path", "import pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport sys\n\n\nplt.rcParams['figure.figsize'] = (19.2, 8.7)\nindex = 0\n\ndef show_accuracy(df):\n\tglobal index\n\t\n\tdf.plot(kind='line')\n\tplt.xlabel('iterations')\n\tplt.ylabel('accuracy')\n\tplt.savefig(str(index) + '.png', bbox_inches='tight')\n\n\tprint('Minima: ' + str(df.min(axis=1).min() * 100) + ' %', file=report)\n\tprint('Primo indice della minima: ' + str(df.min(axis=1).idxmin()), file=report)\n\tprint('Massima: ' + str(df.max(axis=1).max() * 100) + ' %', file=report)\n\tprint('Primo indice della massima: ' + str(df.max(axis=1).idxmax()) + '\\n', file=report)\n\tprint('Finale: ' + str(df[0].iloc[-1]), file=report)\n\n\tindex += 1\n\ndef calculate_node_info(logs):\n\taccuracy_df = pd.read_csv(logs['log_tests.txt'], sep='\\t', header=None)\n\tshow_accuracy(accuracy_df)\n\narch_path = sys.argv[1]\nlogs = {}\nfor nt in os.listdir(arch_path):\n\tif os.path.isdir(os.path.join(arch_path, nt)):\n\t\tnt_path = os.path.join(arch_path, nt)\n\t\tfor ni in os.listdir(nt_path):\n\t\t\tif os.path.isdir(os.path.join(nt_path, ni)):\n\t\t\t\tni_path = os.path.join(os.path.join(nt_path, ni), 'code')\n\t\t\t\tresult = {}\n\t\t\t\tfor log in os.listdir(ni_path):\n\t\t\t\t\tlog_path = os.path.join(ni_path, log)\n\t\t\t\t\tif os.path.isfile(log_path) and 'log' in log:\n\t\t\t\t\t\tresult[log] = log_path\n\t\t\t\tlogs[ni] = result\n\nreport = open('report.txt', 'w')\nprint('\\n------------------- ACCURATEZZA -------------------', file=report)\ncalculate_node_info(logs['edge-0'])\nprint('')" ]
[ [ "tensorflow.Graph", "tensorflow.Session" ], [ "matplotlib.pyplot.xlabel", "pandas.read_csv", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
mwisnie5/pybaseball
[ "0a2a84d757e478aa79619100872ef48cf7da52c5" ]
[ "pybaseball/teamid_lookup.py" ]
[ "import logging\nimport os\nfrom datetime import date\nfrom typing import Optional\n\nimport pandas as pd\n\nfrom . import lahman\nfrom .datasources import fangraphs\n\n_DATA_FILENAME = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'fangraphs_teams.csv')\n\n\ndef team_ids(season: Optional[int] = None, league: str = 'ALL') -> pd.DataFrame:\n if not os.path.exists(_DATA_FILENAME):\n _generate_teams()\n\n fg_team_data = pd.read_csv(_DATA_FILENAME, index_col=0)\n\n if season is not None:\n fg_team_data = fg_team_data.query(f\"yearID == {season}\")\n\n if league is not None and league.upper() != \"ALL\":\n fg_team_data = fg_team_data.query(f\"lgID == '{league.upper()}'\")\n\n return fg_team_data\n\n\n_known_cities = ['Altoona', 'Anaheim', 'Arizona', 'Atlanta', 'Baltimore', 'Boston', 'Brooklyn', 'Buffalo',\n 'California', 'Chicago', 'Cincinnati', 'Cleveland', 'Colorado', 'Detroit', 'Elizabeth', 'Florida',\n 'Fort Wayne', 'Hartford', 'Houston', 'Indianapolis', 'Kansas City', 'Los Angeles', 'Milwaukee',\n 'Minnesota', 'Montreal', 'New York', 'Newark', 'Oakland', 'Philadelphia', 'Pittsburg',\n 'Pittsburgh', 'Richmond', 'San Diego', 'San Francisco', 'Seattle', 'St. Louis', 'St. Paul',\n 'Syracuse', 'Tampa Bay', 'Texas', 'Toronto', 'Troy', 'Washington', 'Washington', 'Wilmington']\n\n_manual_matches = {'CPI': 'Browns/Stogies', 'ANA': 'Angels'}\n\n\ndef _estimate_name(team_row: pd.DataFrame, column: str) -> str:\n if team_row['franchID'] in _manual_matches:\n return _manual_matches[team_row['franchID']]\n estimate = str(team_row[column])\n for city in _known_cities + [str(team_row['city'])]:\n estimate = estimate.replace(f'{city} ', '') if estimate.startswith(city) else estimate\n\n return estimate\n\n\ndef _generate_teams() -> pd.DataFrame:\n \"\"\"\n Creates a datafile with a map of Fangraphs team IDs to lahman data to be used by fangraphss_teams\n\n Should only need to be run when a team is added, removed, or moves to a new city.\n \"\"\"\n\n start_season = 1871\n end_season = date.today().year\n\n # Only getting AB to make payload small, and you have to specify at least one column\n team_data = fangraphs.fg_team_batting_data(start_season, end_season, \"ALL\", stat_columns=['AB'])\n\n # Join the lahman data\n teams_franchises = lahman.teams().merge(lahman.teams_franchises(), how='left', on='franchID', suffixes=['', '.fr'])\n teams_franchises = teams_franchises.merge(lahman.parks(), how='left', left_on='park', right_on='park.name',\n suffixes=['', '.p'])\n\n # Drop lahman data down to just what we need\n teams_franchises = teams_franchises[\n ['yearID', 'lgID', 'teamID', 'franchID', 'divID', 'name', 'park', 'teamIDBR', 'teamIDlahman45', 'teamIDretro',\n 'franchName', 'city', 'state']\n ]\n\n # Try to guess the name Fangraphs would use\n teams_franchises['possibleName'] = teams_franchises.apply(lambda row: _estimate_name(row, 'name'), axis=1)\n teams_franchises['possibleFranchName'] = teams_franchises.apply(lambda row: _estimate_name(row, 'franchName'),\n axis=1)\n\n # Join up the data by team name, and look for what is still without a match\n outer_joined = teams_franchises.merge(team_data, how='outer', left_on=['yearID', 'possibleName'],\n right_on=['Season', 'Team'])\n unjoined_teams_franchises = outer_joined.query('Season.isnull()').drop(team_data.columns, axis=1)\n unjoined_team_data = outer_joined.query('yearID.isnull()').drop(teams_franchises.columns, axis=1)\n\n # Take all the unmatched data and try to join off franchise name, instead of team name\n inner_joined = teams_franchises.merge(team_data, how='inner', left_on=['yearID', 'possibleName'],\n right_on=['Season', 'Team'])\n franch_inner_joined = unjoined_teams_franchises.merge(unjoined_team_data, how='inner',\n left_on=['yearID', 'possibleFranchName'],\n right_on=['Season', 'Team'])\n\n # Clean up the data\n joined = pd.concat([inner_joined, franch_inner_joined])\n\n outer_joined = joined.merge(team_data, how='outer', left_on=['yearID', 'teamIDfg'],\n right_on=['Season', 'teamIDfg'], suffixes=['', '_y'])\n\n unjoined_teams_franchises = outer_joined.query('Season_y.isnull()').drop(team_data.columns, axis=1,\n errors='ignore')\n\n if not unjoined_teams_franchises.empty:\n logging.warning('When trying to join FG data to lahman, found the following extraneous lahman data',\n extra=unjoined_teams_franchises)\n\n unjoined_team_data = outer_joined.query('yearID.isnull()').drop(teams_franchises.columns, axis=1, errors='ignore')\n\n if not unjoined_team_data.empty:\n logging.warning('When trying to join Fangraphs data to lahman, found the following extraneous Fangraphs data',\n extra=unjoined_team_data)\n\n joined = joined[['yearID', 'lgID', 'teamID', 'franchID', 'teamIDfg', 'teamIDBR', 'teamIDretro']]\n\n joined = joined.assign(teamIDfg=joined['teamIDfg'].apply(int))\n joined = joined.assign(yearID=joined['yearID'].apply(int))\n\n joined = joined.sort_values(['yearID', 'lgID', 'teamID', 'franchID']).drop_duplicates()\n joined = joined.reset_index(drop=True)\n\n joined.to_csv(_DATA_FILENAME)\n\n return joined\n\n# For backwards API compatibility\nfangraphs_teams = team_ids\n" ]
[ [ "pandas.concat", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
micsthepick/boxed-bottles
[ "424cc0aec3e5d6897a38fc0507d9c609c9f78a1e" ]
[ "object_detection/utils/variables_helper.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Helper functions for manipulating collections of variables during training.\n\"\"\"\nfrom tensorflow import logging as logging\nimport re\n\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import variables as tf_variables\n\nslim = tf.contrib.slim\n\n\n# TODO(derekjchow): Consider replacing with tf.contrib.filter_variables in\n# tensorflow/contrib/framework/python/ops/variables.py\ndef filter_variables(variables, filter_regex_list, invert=False):\n \"\"\"Filters out the variables matching the filter_regex.\n\n Filter out the variables whose name matches the any of the regular\n expressions in filter_regex_list and returns the remaining variables.\n Optionally, if invert=True, the complement set is returned.\n\n Args:\n variables: a list of tensorflow variables.\n filter_regex_list: a list of string regular expressions.\n invert: (boolean). If True, returns the complement of the filter set; that\n is, all variables matching filter_regex are kept and all others discarded.\n\n Returns:\n a list of filtered variables.\n \"\"\"\n kept_vars = []\n variables_to_ignore_patterns = list(filter(None, filter_regex_list))\n for var in variables:\n add = True\n for pattern in variables_to_ignore_patterns:\n if re.match(pattern, var.op.name):\n add = False\n break\n if add != invert:\n kept_vars.append(var)\n return kept_vars\n\n\ndef multiply_gradients_matching_regex(grads_and_vars, regex_list, multiplier):\n \"\"\"Multiply gradients whose variable names match a regular expression.\n\n Args:\n grads_and_vars: A list of gradient to variable pairs (tuples).\n regex_list: A list of string regular expressions.\n multiplier: A (float) multiplier to apply to each gradient matching the\n regular expression.\n\n Returns:\n grads_and_vars: A list of gradient to variable pairs (tuples).\n \"\"\"\n variables = [pair[1] for pair in grads_and_vars]\n matching_vars = filter_variables(variables, regex_list, invert=True)\n for var in matching_vars:\n logging.info('Applying multiplier %f to variable [%s]',\n multiplier, var.op.name)\n grad_multipliers = {var: float(multiplier) for var in matching_vars}\n return slim.learning.multiply_gradients(grads_and_vars,\n grad_multipliers)\n\n\ndef freeze_gradients_matching_regex(grads_and_vars, regex_list):\n \"\"\"Freeze gradients whose variable names match a regular expression.\n\n Args:\n grads_and_vars: A list of gradient to variable pairs (tuples).\n regex_list: A list of string regular expressions.\n\n Returns:\n grads_and_vars: A list of gradient to variable pairs (tuples) that do not\n contain the variables and gradients matching the regex.\n \"\"\"\n variables = [pair[1] for pair in grads_and_vars]\n matching_vars = filter_variables(variables, regex_list, invert=True)\n kept_grads_and_vars = [pair for pair in grads_and_vars\n if pair[1] not in matching_vars]\n for var in matching_vars:\n logging.info('Freezing variable [%s]', var.op.name)\n return kept_grads_and_vars\n\n\ndef get_variables_available_in_checkpoint(variables,\n checkpoint_path,\n include_global_step=True):\n \"\"\"Returns the subset of variables available in the checkpoint.\n\n Inspects given checkpoint and returns the subset of variables that are\n available in it.\n\n TODO(rathodv): force input and output to be a dictionary.\n\n Args:\n variables: a list or dictionary of variables to find in checkpoint.\n checkpoint_path: path to the checkpoint to restore variables from.\n include_global_step: whether to include `global_step` variable, if it\n exists. Default True.\n\n Returns:\n A list or dictionary of variables.\n Raises:\n ValueError: if `variables` is not a list or dict.\n \"\"\"\n if isinstance(variables, list):\n variable_names_map = {}\n for variable in variables:\n if isinstance(variable, tf_variables.PartitionedVariable):\n name = variable.name\n else:\n name = variable.op.name\n variable_names_map[name] = variable\n elif isinstance(variables, dict):\n variable_names_map = variables\n else:\n raise ValueError('`variables` is expected to be a list or dict.')\n ckpt_reader = tf.train.NewCheckpointReader(checkpoint_path)\n ckpt_vars_to_shape_map = ckpt_reader.get_variable_to_shape_map()\n if not include_global_step:\n ckpt_vars_to_shape_map.pop(tf.GraphKeys.GLOBAL_STEP, None)\n vars_in_ckpt = {}\n for variable_name, variable in sorted(variable_names_map.items()):\n if variable_name in ckpt_vars_to_shape_map:\n if ckpt_vars_to_shape_map[variable_name] == variable.shape.as_list():\n vars_in_ckpt[variable_name] = variable\n else:\n logging.warning('Variable [%s] is available in checkpoint, but has an '\n 'incompatible shape with model variable. Checkpoint '\n 'shape: [%s], model variable shape: [%s]. This '\n 'variable will not be initialized from the checkpoint.',\n variable_name, ckpt_vars_to_shape_map[variable_name],\n variable.shape.as_list())\n else:\n logging.warning('Variable [%s] is not available in checkpoint',\n variable_name)\n if isinstance(variables, list):\n return vars_in_ckpt.values()\n return vars_in_ckpt\n" ]
[ [ "tensorflow.logging.warning", "tensorflow.train.NewCheckpointReader", "tensorflow.logging.info" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
connectthefuture/tensorflow
[ "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d", "93812423fcd5878aa2c1d0b68dc0496980c8519d" ]
[ "tensorflow/contrib/seq2seq/python/kernel_tests/seq2seq_test.py", "tensorflow/python/training/device_setter_test.py", "tensorflow/python/ops/parsing_ops.py", "tensorflow/tools/test/run_and_gather_logs_lib.py", "tensorflow/tensorboard/backend/handler_test.py", "tensorflow/python/kernel_tests/pool_test.py", "tensorflow/contrib/distributions/python/ops/relaxed_bernoulli.py", "tensorflow/python/summary/impl/directory_watcher.py", "tensorflow/contrib/learn/python/learn/experiment_test.py", "tensorflow/python/framework/errors_impl.py", "tensorflow/python/kernel_tests/barrier_ops_test.py", "tensorflow/python/training/moving_averages.py", "tensorflow/python/kernel_tests/benchmark_test.py", "tensorflow/examples/learn/text_classification_character_cnn.py", "tensorflow/python/debug/debug_utils_test.py", "tensorflow/contrib/learn/python/learn/ops/losses_ops.py", "tensorflow/python/util/keyword_args_test.py", "tensorflow/python/kernel_tests/sparse_tensors_map_ops_test.py", "tensorflow/contrib/factorization/python/kernel_tests/clustering_ops_test.py", "tensorflow/python/kernel_tests/parameterized_truncated_normal_op_test.py", "tensorflow/python/ops/math_grad_test.py", "tensorflow/contrib/learn/python/learn/metric_spec.py" ]
[ "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for contrib.seq2seq.python.ops.seq2seq.\"\"\"\n# pylint: disable=unused-import,g-bad-import-order\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n# pylint: enable=unused-import\n\nimport tensorflow as tf\nfrom tensorflow.contrib import layers\n\nclass Seq2SeqTest(tf.test.TestCase):\n\n # test a default call of rnn_decoder\n def test_rnn_decoder(self):\n pass\n\n # test default call with time_major=True\n def test_dynamic_rnn_decoder_time_major(self):\n with self.test_session() as sess:\n with tf.variable_scope(\"root\", initializer=\n tf.constant_initializer(0.5)) as varscope:\n # Define inputs/outputs to model\n batch_size = 2\n encoder_embedding_size = 3\n decoder_embedding_size = 4\n encoder_hidden_size = 5\n decoder_hidden_size = encoder_hidden_size\n input_sequence_length = 6\n decoder_sequence_length = 7\n num_decoder_symbols = 20\n start_of_sequence_id = end_of_sequence_id = 1\n decoder_embeddings = tf.get_variable('decoder_embeddings',\n [num_decoder_symbols, decoder_embedding_size],\n initializer=tf.random_normal_initializer(stddev=0.1))\n inputs = tf.constant(0.5, shape=[input_sequence_length, batch_size,\n encoder_embedding_size])\n decoder_inputs = tf.constant(0.4, shape=[decoder_sequence_length,\n batch_size,\n decoder_embedding_size])\n decoder_length = tf.constant(decoder_sequence_length, dtype=tf.int32,\n shape=[batch_size,])\n with tf.variable_scope(\"rnn\") as scope:\n # setting up weights for computing the final output\n output_fn = lambda x: layers.linear(x, num_decoder_symbols,\n scope=scope)\n\n # Define model\n encoder_outputs, encoder_state = tf.nn.dynamic_rnn(\n cell=tf.nn.rnn_cell.GRUCell(encoder_hidden_size), inputs=inputs,\n dtype=tf.float32, time_major=True, scope=scope)\n\n\n with tf.variable_scope(\"decoder\") as scope:\n # Train decoder\n decoder_cell = tf.nn.rnn_cell.GRUCell(decoder_hidden_size)\n decoder_fn_train = tf.contrib.seq2seq.simple_decoder_fn_train(\n encoder_state=encoder_state)\n decoder_outputs_train, decoder_state_train = (\n tf.contrib.seq2seq.dynamic_rnn_decoder(\n cell=decoder_cell,\n decoder_fn=decoder_fn_train,\n inputs=decoder_inputs,\n sequence_length=decoder_length,\n time_major=True,\n scope=scope))\n decoder_outputs_train = output_fn(decoder_outputs_train)\n\n # Setup variable reuse\n scope.reuse_variables()\n\n # Inference decoder\n decoder_fn_inference = (\n tf.contrib.seq2seq.simple_decoder_fn_inference(\n output_fn=output_fn,\n encoder_state=encoder_state,\n embeddings=decoder_embeddings,\n start_of_sequence_id=start_of_sequence_id,\n end_of_sequence_id=end_of_sequence_id,\n #TODO: find out why it goes to +1\n maximum_length=decoder_sequence_length-1,\n num_decoder_symbols=num_decoder_symbols,\n dtype=tf.int32))\n decoder_outputs_inference, decoder_state_inference = (\n tf.contrib.seq2seq.dynamic_rnn_decoder(\n cell=decoder_cell,\n decoder_fn=decoder_fn_inference,\n time_major=True,\n scope=scope))\n\n # Run model\n tf.global_variables_initializer().run()\n decoder_outputs_train_res, decoder_state_train_res = sess.run(\n [decoder_outputs_train, decoder_state_train])\n decoder_outputs_inference_res, decoder_state_inference_res = sess.run(\n [decoder_outputs_inference, decoder_state_inference])\n\n # Assert outputs\n self.assertEqual((decoder_sequence_length, batch_size,\n num_decoder_symbols),\n decoder_outputs_train_res.shape)\n self.assertEqual((batch_size, num_decoder_symbols),\n decoder_outputs_inference_res.shape[1:3])\n self.assertEqual((batch_size, decoder_hidden_size),\n decoder_state_train_res.shape)\n self.assertEqual((batch_size, decoder_hidden_size),\n decoder_state_inference_res.shape)\n # The dynamic decoder might end earlier than `maximal_length`\n # under inference\n true_value = (decoder_sequence_length>=\n decoder_state_inference_res.shape[0])\n self.assertEqual((true_value), True)\n\nif __name__ == '__main__':\n tf.test.main()\n", "# 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# ==============================================================================\n\"\"\"Tests for device function for replicated training.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\nclass DeviceSetterTest(tf.test.TestCase):\n\n _cluster_spec = tf.train.ClusterSpec({\n \"ps\": [\"ps0:2222\", \"ps1:2222\"],\n \"worker\": [\"worker0:2222\", \"worker1:2222\", \"worker2:2222\"]})\n\n def testCPUOverride(self):\n with tf.device(tf.train.replica_device_setter(cluster=self._cluster_spec)):\n with tf.device(\"/cpu:0\"):\n v = tf.Variable([1, 2])\n w = tf.Variable([2, 1])\n with tf.device(\"/cpu:0\"):\n a = v + w\n self.assertDeviceEqual(\"/job:ps/task:0/cpu:0\", v.device)\n self.assertDeviceEqual(\"/job:ps/task:0/cpu:0\", v.initializer.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.initializer.device)\n self.assertDeviceEqual(\"/job:worker/cpu:0\", a.device)\n\n def testPS2TasksWithClusterSpecClass(self):\n with tf.device(tf.train.replica_device_setter(cluster=self._cluster_spec)):\n v = tf.Variable([1, 2])\n w = tf.Variable([2, 1])\n a = v + w\n self.assertDeviceEqual(\"/job:ps/task:0\", v.device)\n self.assertDeviceEqual(\"/job:ps/task:0\", v.initializer.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.initializer.device)\n self.assertDeviceEqual(\"/job:worker\", a.device)\n\n def testPS2TasksWithClusterSpecDict(self):\n with tf.device(tf.train.replica_device_setter(\n cluster=self._cluster_spec.as_dict())):\n v = tf.Variable([1, 2])\n w = tf.Variable([2, 1])\n a = v + w\n self.assertDeviceEqual(\"/job:ps/task:0\", v.device)\n self.assertDeviceEqual(\"/job:ps/task:0\", v.initializer.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.initializer.device)\n self.assertDeviceEqual(\"/job:worker\", a.device)\n\n def testPS2TasksWithClusterDef(self):\n with tf.device(tf.train.replica_device_setter(\n cluster=self._cluster_spec.as_cluster_def())):\n v = tf.Variable([1, 2])\n w = tf.Variable([2, 1])\n a = v + w\n self.assertDeviceEqual(\"/job:ps/task:0\", v.device)\n self.assertDeviceEqual(\"/job:ps/task:0\", v.initializer.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.device)\n self.assertDeviceEqual(\"/job:ps/task:1\", w.initializer.device)\n self.assertDeviceEqual(\"/job:worker\", a.device)\n\n def testPS2TasksWithDevice(self):\n cluster_spec = tf.train.ClusterSpec({\n \"sun\": [\"sun0:2222\", \"sun1:2222\", \"sun2:2222\"],\n \"moon\": [\"moon0:2222\", \"moon1:2222\"]})\n\n with tf.device(tf.train.replica_device_setter(\n ps_device=\"/job:moon\", worker_device=\"/job:sun\",\n cluster=cluster_spec.as_cluster_def())):\n v = tf.Variable([1, 2])\n w = tf.Variable([2, 1])\n a = v + w\n self.assertDeviceEqual(\"/job:moon/task:0\", v.device)\n self.assertDeviceEqual(\"/job:moon/task:0\", v.initializer.device)\n self.assertDeviceEqual(\"/job:moon/task:1\", w.device)\n self.assertDeviceEqual(\"/job:moon/task:1\", w.initializer.device)\n self.assertDeviceEqual(\"/job:sun\", a.device)\n\n def testPS2TasksWithCPUConstraint(self):\n cluster_spec = tf.train.ClusterSpec({\n \"sun\": [\"sun0:2222\", \"sun1:2222\", \"sun2:2222\"],\n \"moon\": [\"moon0:2222\", \"moon1:2222\"]})\n\n with tf.device(tf.train.replica_device_setter(\n ps_device=\"/job:moon/cpu:0\", worker_device=\"/job:sun\",\n cluster=cluster_spec.as_cluster_def())):\n v = tf.Variable([1, 2])\n w = tf.Variable([2, 1])\n a = v + w\n self.assertDeviceEqual(\"/job:moon/task:0/cpu:0\", v.device)\n self.assertDeviceEqual(\"/job:moon/task:0/cpu:0\", v.initializer.device)\n self.assertDeviceEqual(\"/job:moon/task:1/cpu:0\", w.device)\n self.assertDeviceEqual(\"/job:moon/task:1/cpu:0\", w.initializer.device)\n self.assertDeviceEqual(\"/job:sun\", a.device)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# 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# ==============================================================================\n\n\"\"\"Parsing Ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport re\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_parsing_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import sparse_ops\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import,undefined-variable\nfrom tensorflow.python.ops.gen_parsing_ops import *\n# pylint: enable=wildcard-import,undefined-variable\n\n\nops.NotDifferentiable(\"DecodeRaw\")\nops.NotDifferentiable(\"ParseTensor\")\nops.NotDifferentiable(\"StringToNumber\")\n\n\nclass VarLenFeature(collections.namedtuple(\"VarLenFeature\", [\"dtype\"])):\n \"\"\"Configuration for parsing a variable-length input feature.\n\n Fields:\n dtype: Data type of input.\n \"\"\"\n pass\n\n\nclass SparseFeature(\n collections.namedtuple(\n \"SparseFeature\",\n [\"index_key\", \"value_key\", \"dtype\", \"size\", \"already_sorted\"])):\n \"\"\"Configuration for parsing a sparse input feature.\n\n Fields:\n index_key: Name of index feature. The underlying feature's type must\n be `int64` and its length must always match that of the `value_key`\n feature.\n value_key: Name of value feature. The underlying feature's type must\n be `dtype` and its length must always match that of the `index_key`\n feature.\n dtype: Data type of the `value_key` feature.\n size: Each value in the `index_key` feature must be in `[0, size)`.\n already_sorted: A boolean to specify whether the values in `index_key` are\n already sorted. If so skip sorting, False by default (optional).\n \"\"\"\n pass\nSparseFeature.__new__.__defaults__ = (False,)\n\n\nclass FixedLenFeature(collections.namedtuple(\n \"FixedLenFeature\", [\"shape\", \"dtype\", \"default_value\"])):\n \"\"\"Configuration for parsing a fixed-length input feature.\n\n To treat sparse input as dense, provide a `default_value`; otherwise,\n the parse functions will fail on any examples missing this feature.\n\n Fields:\n shape: Shape of input data.\n dtype: Data type of input.\n default_value: Value to be used if an example is missing this feature. It\n must be compatible with `dtype`.\n \"\"\"\n pass\nFixedLenFeature.__new__.__defaults__ = (None,)\n\n\n# NOTE: If we ever support a default_value for sequence dense features, we can\n# remove this class and use FixedLenFeature in its place.\nclass FixedLenSequenceFeature(collections.namedtuple(\n \"FixedLenSequenceFeature\", [\"shape\", \"dtype\", \"allow_missing\"])):\n \"\"\"Configuration for a dense input feature in a sequence item.\n\n To treat a sparse input as dense, provide `allow_missing=True`; otherwise,\n the parse functions will fail on any examples missing this feature.\n\n Fields:\n shape: Shape of input data.\n dtype: Data type of input.\n allow_missing: Whether to allow this feature to be missing from a feature\n list item.\n \"\"\"\n pass\nFixedLenSequenceFeature.__new__.__defaults__ = (False,)\n\n\ndef _features_to_raw_params(features, types):\n \"\"\"Split feature tuples into raw params used by `gen_parsing_ops`.\n\n Args:\n features: A `dict` mapping feature keys to objects of a type in `types`.\n types: Type of features to allow, among `FixedLenFeature`, `VarLenFeature`,\n `SparseFeature`, and `FixedLenSequenceFeature`.\n\n Returns:\n Tuple of `sparse_keys`, `sparse_types`, `dense_keys`, `dense_types`,\n `dense_defaults`, `dense_shapes`.\n\n Raises:\n ValueError: if `features` contains an item not in `types`, or an invalid\n feature.\n \"\"\"\n sparse_keys = []\n sparse_types = []\n dense_keys = []\n dense_types = []\n dense_defaults = {}\n dense_shapes = []\n if features:\n # NOTE: We iterate over sorted keys to keep things deterministic.\n for key in sorted(features.keys()):\n feature = features[key]\n if isinstance(feature, VarLenFeature):\n if VarLenFeature not in types:\n raise ValueError(\"Unsupported VarLenFeature %s.\", feature)\n if not feature.dtype:\n raise ValueError(\"Missing type for feature %s.\" % key)\n sparse_keys.append(key)\n sparse_types.append(feature.dtype)\n elif isinstance(feature, SparseFeature):\n if SparseFeature not in types:\n raise ValueError(\"Unsupported SparseFeature %s.\", feature)\n if not feature.index_key:\n raise ValueError(\n \"Missing index_key for SparseFeature %s.\", feature)\n if not feature.value_key:\n raise ValueError(\n \"Missing value_key for SparseFeature %s.\", feature)\n if not feature.dtype:\n raise ValueError(\"Missing type for feature %s.\" % key)\n if feature.index_key in sparse_keys:\n dtype = sparse_types[sparse_keys.index(feature.index_key)]\n if dtype != dtypes.int64:\n raise ValueError(\"Conflicting type %s vs int64 for feature %s.\" % (\n dtype, feature.index_key))\n else:\n sparse_keys.append(feature.index_key)\n sparse_types.append(dtypes.int64)\n\n if feature.value_key in sparse_keys:\n dtype = sparse_types[sparse_keys.index(feature.value_key)]\n if dtype != feature.dtype:\n raise ValueError(\"Conflicting type %s vs %s for feature %s.\" % (\n dtype, feature.dtype, feature.value_key))\n else:\n sparse_keys.append(feature.value_key)\n sparse_types.append(feature.dtype)\n elif isinstance(feature, FixedLenFeature):\n if FixedLenFeature not in types:\n raise ValueError(\"Unsupported FixedLenFeature %s.\", feature)\n if not feature.dtype:\n raise ValueError(\"Missing type for feature %s.\" % key)\n if feature.shape is None:\n raise ValueError(\"Missing shape for feature %s.\" % key)\n dense_keys.append(key)\n dense_shapes.append(feature.shape)\n dense_types.append(feature.dtype)\n if feature.default_value is not None:\n dense_defaults[key] = feature.default_value\n elif isinstance(feature, FixedLenSequenceFeature):\n if FixedLenSequenceFeature not in types:\n raise ValueError(\"Unsupported FixedLenSequenceFeature %s.\", feature)\n if not feature.dtype:\n raise ValueError(\"Missing type for feature %s.\" % key)\n if feature.shape is None:\n raise ValueError(\"Missing shape for feature %s.\" % key)\n dense_keys.append(key)\n dense_shapes.append(feature.shape)\n dense_types.append(feature.dtype)\n if feature.allow_missing:\n dense_defaults[key] = None\n else:\n raise ValueError(\"Invalid feature %s:%s.\" % (key, feature))\n return (\n sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults,\n dense_shapes)\n\n\ndef _construct_sparse_tensors_for_sparse_features(features, tensor_dict):\n \"\"\"Merges SparseTensors of indices and values of SparseFeatures.\n\n Updates `tensor_dict`. For `SparseFeatures` in the values of `features`\n expects their `index_key`s and `index_value`s to be present in `tensor_dict`\n mapping to `SparseTensor`s. Removes those, constructs a single `SparseTensor`\n from them, and adds it to `tensor_dict` with the key from `features`.\n\n Args:\n features: A `dict` mapping feature keys to `SparseFeature` values.\n Values of other types will be ignored.\n tensor_dict: A `dict` mapping feature keys to `Tensor` and `SparseTensor`\n values. Expected to contain keys of the `SparseFeature`s' `index_key`s and\n `value_key`s and mapping them to `SparseTensor`s.\n \"\"\"\n # Construct SparseTensors for SparseFeatures.\n for key in sorted(features.keys()):\n feature = features[key]\n if isinstance(feature, SparseFeature):\n sp_ids = tensor_dict[feature.index_key]\n sp_values = tensor_dict[feature.value_key]\n tensor_dict[key] = sparse_ops.sparse_merge(\n sp_ids,\n sp_values,\n feature.size,\n feature.already_sorted)\n # Remove tensors from dictionary that were only used to construct\n # SparseTensors for SparseFeature.\n for key in set(tensor_dict.keys()) - set(features.keys()):\n del tensor_dict[key]\n\n\ndef parse_example(serialized, features, name=None, example_names=None):\n # pylint: disable=line-too-long\n \"\"\"Parses `Example` protos into a `dict` of tensors.\n\n Parses a number of serialized [`Example`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto)\n protos given in `serialized`.\n\n `example_names` may contain descriptive names for the corresponding serialized\n protos. These may be useful for debugging purposes, but they have no effect on\n the output. If not `None`, `example_names` must be the same length as\n `serialized`.\n\n This op parses serialized examples into a dictionary mapping keys to `Tensor`\n and `SparseTensor` objects. `features` is a dict from keys to `VarLenFeature`,\n `SparseFeature`, and `FixedLenFeature` objects. Each `VarLenFeature`\n and `SparseFeature` is mapped to a `SparseTensor`, and each\n `FixedLenFeature` is mapped to a `Tensor`.\n\n Each `VarLenFeature` maps to a `SparseTensor` of the specified type\n representing a ragged matrix. Its indices are `[batch, index]` where `batch`\n is the batch entry the value is from in `serialized`, and `index` is the\n value's index in the list of values associated with that feature and example.\n\n Each `SparseFeature` maps to a `SparseTensor` of the specified type\n representing a sparse matrix of shape\n `(serialized.size(), SparseFeature.size)`. Its indices are `[batch, index]`\n where `batch` is the batch entry the value is from in `serialized`, and\n `index` is the value's index is given by the values in the\n `SparseFeature.index_key` feature column.\n\n Each `FixedLenFeature` `df` maps to a `Tensor` of the specified type (or\n `tf.float32` if not specified) and shape `(serialized.size(),) + df.shape`.\n\n `FixedLenFeature` entries with a `default_value` are optional. With no default\n value, we will fail if that `Feature` is missing from any example in\n `serialized`.\n\n Examples:\n\n For example, if one expects a `tf.float32` sparse feature `ft` and three\n serialized `Example`s are provided:\n\n ```\n serialized = [\n features\n { feature { key: \"ft\" value { float_list { value: [1.0, 2.0] } } } },\n features\n { feature []},\n features\n { feature { key: \"ft\" value { float_list { value: [3.0] } } }\n ]\n ```\n\n then the output will look like:\n\n ```\n {\"ft\": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]],\n values=[1.0, 2.0, 3.0],\n dense_shape=(3, 2)) }\n ```\n\n Given two `Example` input protos in `serialized`:\n\n ```\n [\n features {\n feature { key: \"kw\" value { bytes_list { value: [ \"knit\", \"big\" ] } } }\n feature { key: \"gps\" value { float_list { value: [] } } }\n },\n features {\n feature { key: \"kw\" value { bytes_list { value: [ \"emmy\" ] } } }\n feature { key: \"dank\" value { int64_list { value: [ 42 ] } } }\n feature { key: \"gps\" value { } }\n }\n ]\n ```\n\n And arguments\n\n ```\n example_names: [\"input0\", \"input1\"],\n features: {\n \"kw\": VarLenFeature(tf.string),\n \"dank\": VarLenFeature(tf.int64),\n \"gps\": VarLenFeature(tf.float32),\n }\n ```\n\n Then the output is a dictionary:\n\n ```python\n {\n \"kw\": SparseTensor(\n indices=[[0, 0], [0, 1], [1, 0]],\n values=[\"knit\", \"big\", \"emmy\"]\n dense_shape=[2, 2]),\n \"dank\": SparseTensor(\n indices=[[1, 0]],\n values=[42],\n dense_shape=[2, 1]),\n \"gps\": SparseTensor(\n indices=[],\n values=[],\n dense_shape=[2, 0]),\n }\n ```\n\n For dense results in two serialized `Example`s:\n\n ```\n [\n features {\n feature { key: \"age\" value { int64_list { value: [ 0 ] } } }\n feature { key: \"gender\" value { bytes_list { value: [ \"f\" ] } } }\n },\n features {\n feature { key: \"age\" value { int64_list { value: [] } } }\n feature { key: \"gender\" value { bytes_list { value: [ \"f\" ] } } }\n }\n ]\n ```\n\n We can use arguments:\n\n ```\n example_names: [\"input0\", \"input1\"],\n features: {\n \"age\": FixedLenFeature([], dtype=tf.int64, default_value=-1),\n \"gender\": FixedLenFeature([], dtype=tf.string),\n }\n ```\n\n And the expected output is:\n\n ```python\n {\n \"age\": [[0], [-1]],\n \"gender\": [[\"f\"], [\"f\"]],\n }\n ```\n\n Given two `Example` input protos in `serialized`:\n\n ```\n [\n features {\n feature { key: \"val\" value { float_list { value: [ 0.5, -1.0 ] } } }\n feature { key: \"ix\" value { int64_list { value: [ 3, 20 ] } } }\n },\n features {\n feature { key: \"val\" value { float_list { value: [ 0.0 ] } } }\n feature { key: \"ix\" value { int64_list { value: [ 42 ] } } }\n }\n ]\n ```\n\n And arguments\n\n ```\n example_names: [\"input0\", \"input1\"],\n features: {\n \"sparse\": SparseFeature(\"ix\", \"val\", tf.float32, 100),\n }\n ```\n\n Then the output is a dictionary:\n\n ```python\n {\n \"sparse\": SparseTensor(\n indices=[[0, 3], [0, 20], [1, 42]],\n values=[0.5, -1.0, 0.0]\n dense_shape=[2, 100]),\n }\n ```\n\n Args:\n serialized: A vector (1-D Tensor) of strings, a batch of binary\n serialized `Example` protos.\n features: A `dict` mapping feature keys to `FixedLenFeature`,\n `VarLenFeature`, and `SparseFeature` values.\n name: A name for this operation (optional).\n example_names: A vector (1-D Tensor) of strings (optional), the names of\n the serialized protos in the batch.\n\n Returns:\n A `dict` mapping feature keys to `Tensor` and `SparseTensor` values.\n\n Raises:\n ValueError: if any feature is invalid.\n \"\"\"\n if not features:\n raise ValueError(\"Missing: features was %s.\" % features)\n (sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults,\n dense_shapes) = _features_to_raw_params(\n features, [VarLenFeature, SparseFeature, FixedLenFeature])\n outputs = _parse_example_raw(\n serialized, example_names, sparse_keys, sparse_types, dense_keys,\n dense_types, dense_defaults, dense_shapes, name)\n _construct_sparse_tensors_for_sparse_features(features, outputs)\n return outputs\n\n\ndef _parse_example_raw(serialized,\n names=None,\n sparse_keys=None,\n sparse_types=None,\n dense_keys=None,\n dense_types=None,\n dense_defaults=None,\n dense_shapes=None,\n name=None):\n \"\"\"Parses `Example` protos.\n\n Args:\n serialized: A vector (1-D Tensor) of strings, a batch of binary\n serialized `Example` protos.\n names: A vector (1-D Tensor) of strings (optional), the names of\n the serialized protos.\n sparse_keys: A list of string keys in the examples' features.\n The results for these keys will be returned as `SparseTensor` objects.\n sparse_types: A list of `DTypes` of the same length as `sparse_keys`.\n Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\n and `tf.string` (`BytesList`) are supported.\n dense_keys: A list of string keys in the examples' features.\n The results for these keys will be returned as `Tensor`s\n dense_types: A list of DTypes of the same length as `dense_keys`.\n Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\n and `tf.string` (`BytesList`) are supported.\n dense_defaults: A dict mapping string keys to `Tensor`s.\n The keys of the dict must match the dense_keys of the feature.\n dense_shapes: A list of tuples with the same length as `dense_keys`.\n The shape of the data for each dense feature referenced by `dense_keys`.\n Required for any input tensors identified by `dense_keys` whose shapes are\n anything other than `[]` or `[1]`.\n name: A name for this operation (optional).\n\n Returns:\n A `dict` mapping keys to `Tensor`s and `SparseTensor`s.\n\n Raises:\n ValueError: If sparse and dense key sets intersect, or input lengths do not\n match up.\n \"\"\"\n with ops.name_scope(name, \"ParseExample\", [serialized, names]):\n names = [] if names is None else names\n dense_defaults = {} if dense_defaults is None else dense_defaults\n sparse_keys = [] if sparse_keys is None else sparse_keys\n sparse_types = [] if sparse_types is None else sparse_types\n dense_keys = [] if dense_keys is None else dense_keys\n dense_types = [] if dense_types is None else dense_types\n dense_shapes = (\n [[]] * len(dense_keys) if dense_shapes is None else dense_shapes)\n\n num_dense = len(dense_keys)\n num_sparse = len(sparse_keys)\n\n if len(dense_shapes) != num_dense:\n raise ValueError(\"len(dense_shapes) != len(dense_keys): %d vs. %d\"\n % (len(dense_shapes), num_dense))\n if len(dense_types) != num_dense:\n raise ValueError(\"len(dense_types) != len(num_dense): %d vs. %d\"\n % (len(dense_types), num_dense))\n if len(sparse_types) != num_sparse:\n raise ValueError(\"len(sparse_types) != len(sparse_keys): %d vs. %d\"\n % (len(sparse_types), num_sparse))\n if num_dense + num_sparse == 0:\n raise ValueError(\"Must provide at least one sparse key or dense key\")\n if not set(dense_keys).isdisjoint(set(sparse_keys)):\n raise ValueError(\n \"Dense and sparse keys must not intersect; intersection: %s\" %\n set(dense_keys).intersection(set(sparse_keys)))\n\n dense_defaults_vec = []\n for i, key in enumerate(dense_keys):\n default_value = dense_defaults.get(key)\n if default_value is None:\n default_value = constant_op.constant([], dtype=dense_types[i])\n elif not isinstance(default_value, ops.Tensor):\n key_name = \"key_\" + re.sub(\"[^A-Za-z0-9_.\\\\-/]\", \"_\", key)\n default_value = ops.convert_to_tensor(\n default_value, dtype=dense_types[i], name=key_name)\n default_value = array_ops.reshape(default_value, dense_shapes[i])\n\n dense_defaults_vec.append(default_value)\n\n dense_shapes = [tensor_shape.as_shape(shape).as_proto()\n for shape in dense_shapes]\n\n # pylint: disable=protected-access\n outputs = gen_parsing_ops._parse_example(\n serialized=serialized,\n names=names,\n dense_defaults=dense_defaults_vec,\n sparse_keys=sparse_keys,\n sparse_types=sparse_types,\n dense_keys=dense_keys,\n dense_shapes=dense_shapes,\n name=name)\n # pylint: enable=protected-access\n\n (sparse_indices, sparse_values, sparse_shapes, dense_values) = outputs\n\n sparse_tensors = [\n sparse_tensor.SparseTensor(ix, val, shape) for (ix, val, shape)\n in zip(sparse_indices, sparse_values, sparse_shapes)]\n\n return dict(zip(sparse_keys + dense_keys, sparse_tensors + dense_values))\n\n\ndef parse_single_example(serialized, features, name=None, example_names=None):\n \"\"\"Parses a single `Example` proto.\n\n Similar to `parse_example`, except:\n\n For dense tensors, the returned `Tensor` is identical to the output of\n `parse_example`, except there is no batch dimension, the output shape is the\n same as the shape given in `dense_shape`.\n\n For `SparseTensor`s, the first (batch) column of the indices matrix is removed\n (the indices matrix is a column vector), the values vector is unchanged, and\n the first (`batch_size`) entry of the shape vector is removed (it is now a\n single element vector).\n\n Args:\n serialized: A scalar string Tensor, a single serialized Example.\n See `_parse_single_example_raw` documentation for more details.\n features: A `dict` mapping feature keys to `FixedLenFeature` or\n `VarLenFeature` values.\n name: A name for this operation (optional).\n example_names: (Optional) A scalar string Tensor, the associated name.\n See `_parse_single_example_raw` documentation for more details.\n\n Returns:\n A `dict` mapping feature keys to `Tensor` and `SparseTensor` values.\n\n Raises:\n ValueError: if any feature is invalid.\n \"\"\"\n if not features:\n raise ValueError(\"Missing features.\")\n (sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults,\n dense_shapes) = _features_to_raw_params(\n features, [VarLenFeature, FixedLenFeature, SparseFeature])\n outputs = _parse_single_example_raw(\n serialized, example_names, sparse_keys, sparse_types, dense_keys,\n dense_types, dense_defaults, dense_shapes, name)\n _construct_sparse_tensors_for_sparse_features(features, outputs)\n return outputs\n\n\ndef _parse_single_example_raw(serialized,\n names=None,\n sparse_keys=None,\n sparse_types=None,\n dense_keys=None,\n dense_types=None,\n dense_defaults=None,\n dense_shapes=None,\n name=None):\n \"\"\"Parses a single `Example` proto.\n\n Args:\n serialized: A scalar string Tensor, a single serialized Example.\n See `_parse_example_raw` documentation for more details.\n names: (Optional) A scalar string Tensor, the associated name.\n See `_parse_example_raw` documentation for more details.\n sparse_keys: See `_parse_example_raw` documentation for more details.\n sparse_types: See `_parse_example_raw` documentation for more details.\n dense_keys: See `_parse_example_raw` documentation for more details.\n dense_types: See `_parse_example_raw` documentation for more details.\n dense_defaults: See `_parse_example_raw` documentation for more details.\n dense_shapes: See `_parse_example_raw` documentation for more details.\n name: A name for this operation (optional).\n\n Returns:\n A `dict` mapping feature keys to `Tensor` and `SparseTensor` values.\n\n Raises:\n ValueError: if any feature is invalid.\n \"\"\"\n with ops.name_scope(name, \"ParseSingleExample\", [serialized, names]):\n serialized = ops.convert_to_tensor(serialized)\n serialized_shape = serialized.get_shape()\n if serialized_shape.ndims is not None:\n if serialized_shape.ndims != 0:\n raise ValueError(\"Input serialized must be a scalar\")\n else:\n serialized = control_flow_ops.with_dependencies(\n [control_flow_ops.Assert(\n math_ops.equal(array_ops.rank(serialized), 0),\n [\"Input serialized must be a scalar\"],\n name=\"SerializedIsScalar\")],\n serialized,\n name=\"SerializedDependencies\")\n serialized = array_ops.expand_dims(serialized, 0)\n if names is not None:\n names = ops.convert_to_tensor(names)\n names_shape = names.get_shape()\n if names_shape.ndims is not None:\n if names_shape.ndims != 0:\n raise ValueError(\"Input names must be a scalar\")\n else:\n names = control_flow_ops.with_dependencies(\n [control_flow_ops.Assert(\n math_ops.equal(array_ops.rank(names), 0),\n [\"Input names must be a scalar\"],\n name=\"NamesIsScalar\")],\n names,\n name=\"NamesDependencies\")\n names = array_ops.expand_dims(names, 0)\n\n outputs = _parse_example_raw(\n serialized,\n names=names,\n sparse_keys=sparse_keys,\n sparse_types=sparse_types,\n dense_keys=dense_keys,\n dense_types=dense_types,\n dense_defaults=dense_defaults,\n dense_shapes=dense_shapes,\n name=name)\n if dense_keys is not None:\n for d in dense_keys:\n d_name = re.sub(\"[^A-Za-z0-9_.\\\\-/]\", \"_\", d)\n outputs[d] = array_ops.squeeze(\n outputs[d], [0], name=\"Squeeze_%s\" % d_name)\n if sparse_keys is not None:\n for s in sparse_keys:\n s_name = re.sub(\"[^A-Za-z0-9_.\\\\-/]\", \"_\", s)\n outputs[s] = sparse_tensor.SparseTensor(\n array_ops.slice(outputs[s].indices,\n [0, 1], [-1, -1], name=\"Slice_Indices_%s\" % s_name),\n outputs[s].values,\n array_ops.slice(outputs[s].dense_shape,\n [1], [-1], name=\"Squeeze_Shape_%s\" % s_name))\n return outputs\n\n\ndef parse_single_sequence_example(\n serialized, context_features=None, sequence_features=None,\n example_name=None, name=None):\n # pylint: disable=line-too-long\n \"\"\"Parses a single `SequenceExample` proto.\n\n Parses a single serialized [`SequenceExample`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto)\n proto given in `serialized`.\n\n This op parses a serialize sequence example into a tuple of dictionaries\n mapping keys to `Tensor` and `SparseTensor` objects respectively.\n The first dictionary contains mappings for keys appearing in\n `context_features`, and the second dictionary contains mappings for keys\n appearing in `sequence_features`.\n\n At least one of `context_features` and `sequence_features` must be provided\n and non-empty.\n\n The `context_features` keys are associated with a `SequenceExample` as a\n whole, independent of time / frame. In contrast, the `sequence_features` keys\n provide a way to access variable-length data within the `FeatureList` section\n of the `SequenceExample` proto. While the shapes of `context_features` values\n are fixed with respect to frame, the frame dimension (the first dimension)\n of `sequence_features` values may vary between `SequenceExample` protos,\n and even between `feature_list` keys within the same `SequenceExample`.\n\n `context_features` contains `VarLenFeature` and `FixedLenFeature` objects.\n Each `VarLenFeature` is mapped to a `SparseTensor`, and each `FixedLenFeature`\n is mapped to a `Tensor`, of the specified type, shape, and default value.\n\n `sequence_features` contains `VarLenFeature` and `FixedLenSequenceFeature`\n objects. Each `VarLenFeature` is mapped to a `SparseTensor`, and each\n `FixedLenSequenceFeature` is mapped to a `Tensor`, each of the specified type.\n The shape will be `(T,) + df.dense_shape` for `FixedLenSequenceFeature` `df`, where\n `T` is the length of the associated `FeatureList` in the `SequenceExample`.\n For instance, `FixedLenSequenceFeature([])` yields a scalar 1-D `Tensor` of\n static shape `[None]` and dynamic shape `[T]`, while\n `FixedLenSequenceFeature([k])` (for `int k >= 1`) yields a 2-D matrix `Tensor`\n of static shape `[None, k]` and dynamic shape `[T, k]`.\n\n Each `SparseTensor` corresponding to `sequence_features` represents a ragged\n vector. Its indices are `[time, index]`, where `time` is the `FeatureList`\n entry and `index` is the value's index in the list of values associated with\n that time.\n\n `FixedLenFeature` entries with a `default_value` and `FixedLenSequenceFeature`\n entries with `allow_missing=True` are optional; otherwise, we will fail if\n that `Feature` or `FeatureList` is missing from any example in `serialized`.\n\n `example_name` may contain a descriptive name for the corresponding serialized\n proto. This may be useful for debugging purposes, but it has no effect on the\n output. If not `None`, `example_name` must be a scalar.\n\n Args:\n serialized: A scalar (0-D Tensor) of type string, a single binary\n serialized `SequenceExample` proto.\n context_features: A `dict` mapping feature keys to `FixedLenFeature` or\n `VarLenFeature` values. These features are associated with a\n `SequenceExample` as a whole.\n sequence_features: A `dict` mapping feature keys to\n `FixedLenSequenceFeature` or `VarLenFeature` values. These features are\n associated with data within the `FeatureList` section of the\n `SequenceExample` proto.\n example_name: A scalar (0-D Tensor) of strings (optional), the name of\n the serialized proto.\n name: A name for this operation (optional).\n\n Returns:\n A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s.\n The first dict contains the context key/values.\n The second dict contains the feature_list key/values.\n\n Raises:\n ValueError: if any feature is invalid.\n \"\"\"\n # pylint: enable=line-too-long\n if not (context_features or sequence_features):\n raise ValueError(\"Missing features.\")\n (context_sparse_keys, context_sparse_types, context_dense_keys,\n context_dense_types, context_dense_defaults,\n context_dense_shapes) = _features_to_raw_params(\n context_features, [VarLenFeature, FixedLenFeature])\n (feature_list_sparse_keys, feature_list_sparse_types,\n feature_list_dense_keys, feature_list_dense_types,\n feature_list_dense_defaults,\n feature_list_dense_shapes) = _features_to_raw_params(\n sequence_features, [VarLenFeature, FixedLenSequenceFeature])\n return _parse_single_sequence_example_raw(\n serialized, context_sparse_keys, context_sparse_types,\n context_dense_keys, context_dense_types, context_dense_defaults,\n context_dense_shapes, feature_list_sparse_keys,\n feature_list_sparse_types, feature_list_dense_keys,\n feature_list_dense_types, feature_list_dense_shapes,\n feature_list_dense_defaults, example_name, name)\n\n\ndef _parse_single_sequence_example_raw(serialized,\n context_sparse_keys=None,\n context_sparse_types=None,\n context_dense_keys=None,\n context_dense_types=None,\n context_dense_defaults=None,\n context_dense_shapes=None,\n feature_list_sparse_keys=None,\n feature_list_sparse_types=None,\n feature_list_dense_keys=None,\n feature_list_dense_types=None,\n feature_list_dense_shapes=None,\n feature_list_dense_defaults=None,\n debug_name=None,\n name=None):\n \"\"\"Parses a single `SequenceExample` proto.\n\n Args:\n serialized: A scalar (0-D Tensor) of type string, a single binary\n serialized `SequenceExample` proto.\n context_sparse_keys: A list of string keys in the `SequenceExample`'s\n features. The results for these keys will be returned as\n `SparseTensor` objects.\n context_sparse_types: A list of `DTypes`, the same length as `sparse_keys`.\n Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\n and `tf.string` (`BytesList`) are supported.\n context_dense_keys: A list of string keys in the examples' features.\n The results for these keys will be returned as `Tensor`s\n context_dense_types: A list of DTypes, same length as `context_dense_keys`.\n Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\n and `tf.string` (`BytesList`) are supported.\n context_dense_defaults: A dict mapping string keys to `Tensor`s.\n The keys of the dict must match the context_dense_keys of the feature.\n context_dense_shapes: A list of tuples, same length as `context_dense_keys`.\n The shape of the data for each context_dense feature referenced by\n `context_dense_keys`. Required for any input tensors identified by\n `context_dense_keys` whose shapes are anything other than `[]` or `[1]`.\n feature_list_sparse_keys: A list of string keys in the `SequenceExample`'s\n feature_lists. The results for these keys will be returned as\n `SparseTensor` objects.\n feature_list_sparse_types: A list of `DTypes`, same length as `sparse_keys`.\n Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\n and `tf.string` (`BytesList`) are supported.\n feature_list_dense_keys: A list of string keys in the `SequenceExample`'s\n features_lists. The results for these keys will be returned as `Tensor`s.\n feature_list_dense_types: A list of `DTypes`, same length as\n `feature_list_dense_keys`. Only `tf.float32` (`FloatList`),\n `tf.int64` (`Int64List`), and `tf.string` (`BytesList`) are supported.\n feature_list_dense_shapes: A list of tuples, same length as\n `feature_list_dense_keys`. The shape of the data for each\n `FeatureList` feature referenced by `feature_list_dense_keys`.\n feature_list_dense_defaults: A dict mapping key strings to values.\n The only currently allowed value is `None`. Any key appearing\n in this dict with value `None` is allowed to be missing from the\n `SequenceExample`. If missing, the key is treated as zero-length.\n debug_name: A scalar (0-D Tensor) of strings (optional), the name of\n the serialized proto.\n name: A name for this operation (optional).\n\n Returns:\n A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s.\n The first dict contains the context key/values.\n The second dict contains the feature_list key/values.\n\n Raises:\n ValueError: If context_sparse and context_dense key sets intersect,\n if input lengths do not match up, or if a value in\n feature_list_dense_defaults is not None.\n TypeError: if feature_list_dense_defaults is not either None or a dict.\n \"\"\"\n with ops.name_scope(name, \"ParseSingleSequenceExample\", [serialized]):\n context_dense_defaults = (\n {} if context_dense_defaults is None else context_dense_defaults)\n context_sparse_keys = (\n [] if context_sparse_keys is None else context_sparse_keys)\n context_sparse_types = (\n [] if context_sparse_types is None else context_sparse_types)\n context_dense_keys = (\n [] if context_dense_keys is None else context_dense_keys)\n context_dense_types = (\n [] if context_dense_types is None else context_dense_types)\n context_dense_shapes = (\n [[]] * len(context_dense_keys)\n if context_dense_shapes is None else context_dense_shapes)\n feature_list_sparse_keys = (\n [] if feature_list_sparse_keys is None else feature_list_sparse_keys)\n feature_list_sparse_types = (\n [] if feature_list_sparse_types is None else feature_list_sparse_types)\n feature_list_dense_keys = (\n [] if feature_list_dense_keys is None else feature_list_dense_keys)\n feature_list_dense_types = (\n [] if feature_list_dense_types is None else feature_list_dense_types)\n feature_list_dense_shapes = (\n [[]] * len(feature_list_dense_keys)\n if feature_list_dense_shapes is None else feature_list_dense_shapes)\n feature_list_dense_defaults = (\n dict() if feature_list_dense_defaults is None\n else feature_list_dense_defaults)\n debug_name = \"\" if debug_name is None else debug_name\n\n # Internal\n feature_list_dense_missing_assumed_empty = []\n\n num_context_dense = len(context_dense_keys)\n num_feature_list_dense = len(feature_list_dense_keys)\n num_context_sparse = len(context_sparse_keys)\n num_feature_list_sparse = len(feature_list_sparse_keys)\n\n if len(context_dense_shapes) != num_context_dense:\n raise ValueError(\n \"len(context_dense_shapes) != len(context_dense_keys): %d vs. %d\"\n % (len(context_dense_shapes), num_context_dense))\n if len(context_dense_types) != num_context_dense:\n raise ValueError(\n \"len(context_dense_types) != len(num_context_dense): %d vs. %d\"\n % (len(context_dense_types), num_context_dense))\n if len(feature_list_dense_shapes) != num_feature_list_dense:\n raise ValueError(\n \"len(feature_list_dense_shapes) != len(feature_list_dense_keys): \"\n \"%d vs. %d\" % (len(feature_list_dense_shapes),\n num_feature_list_dense))\n if len(feature_list_dense_types) != num_feature_list_dense:\n raise ValueError(\n \"len(feature_list_dense_types) != len(num_feature_list_dense):\"\n \"%d vs. %d\" % (len(feature_list_dense_types), num_feature_list_dense))\n if len(context_sparse_types) != num_context_sparse:\n raise ValueError(\n \"len(context_sparse_types) != len(context_sparse_keys): %d vs. %d\"\n % (len(context_sparse_types), num_context_sparse))\n if len(feature_list_sparse_types) != num_feature_list_sparse:\n raise ValueError(\n \"len(feature_list_sparse_types) != len(feature_list_sparse_keys): \"\n \"%d vs. %d\"\n % (len(feature_list_sparse_types), num_feature_list_sparse))\n if (num_context_dense + num_context_sparse\n + num_feature_list_dense + num_feature_list_sparse) == 0:\n raise ValueError(\n \"Must provide at least one context_sparse key, context_dense key, \"\n \", feature_list_sparse key, or feature_list_dense key\")\n if not set(context_dense_keys).isdisjoint(set(context_sparse_keys)):\n raise ValueError(\n \"context_dense and context_sparse keys must not intersect; \"\n \"intersection: %s\" %\n set(context_dense_keys).intersection(set(context_sparse_keys)))\n if not set(feature_list_dense_keys).isdisjoint(\n set(feature_list_sparse_keys)):\n raise ValueError(\n \"feature_list_dense and feature_list_sparse keys must not intersect; \"\n \"intersection: %s\" %\n set(feature_list_dense_keys).intersection(\n set(feature_list_sparse_keys)))\n if not isinstance(feature_list_dense_defaults, dict):\n raise TypeError(\"feature_list_dense_defaults must be a dict\")\n for k, v in feature_list_dense_defaults.items():\n if v is not None:\n raise ValueError(\"Value feature_list_dense_defaults[%s] must be None\"\n % k)\n feature_list_dense_missing_assumed_empty.append(k)\n\n context_dense_defaults_vec = []\n for i, key in enumerate(context_dense_keys):\n default_value = context_dense_defaults.get(key)\n if default_value is None:\n default_value = constant_op.constant([], dtype=context_dense_types[i])\n elif not isinstance(default_value, ops.Tensor):\n key_name = \"key_\" + re.sub(\"[^A-Za-z0-9_.\\\\-/]\", \"_\", key)\n default_value = ops.convert_to_tensor(\n default_value, dtype=context_dense_types[i], name=key_name)\n default_value = array_ops.reshape(\n default_value, context_dense_shapes[i])\n\n context_dense_defaults_vec.append(default_value)\n\n context_dense_shapes = [tensor_shape.as_shape(shape).as_proto()\n for shape in context_dense_shapes]\n feature_list_dense_shapes = [tensor_shape.as_shape(shape).as_proto()\n for shape in feature_list_dense_shapes]\n\n # pylint: disable=protected-access\n outputs = gen_parsing_ops._parse_single_sequence_example(\n serialized=serialized,\n debug_name=debug_name,\n context_dense_defaults=context_dense_defaults_vec,\n context_sparse_keys=context_sparse_keys,\n context_sparse_types=context_sparse_types,\n context_dense_keys=context_dense_keys,\n context_dense_shapes=context_dense_shapes,\n feature_list_sparse_keys=feature_list_sparse_keys,\n feature_list_sparse_types=feature_list_sparse_types,\n feature_list_dense_keys=feature_list_dense_keys,\n feature_list_dense_types=feature_list_dense_types,\n feature_list_dense_shapes=feature_list_dense_shapes,\n feature_list_dense_missing_assumed_empty=(\n feature_list_dense_missing_assumed_empty),\n name=name)\n # pylint: enable=protected-access\n\n (context_sparse_indices, context_sparse_values,\n context_sparse_shapes, context_dense_values,\n feature_list_sparse_indices, feature_list_sparse_values,\n feature_list_sparse_shapes, feature_list_dense_values) = outputs\n\n context_sparse_tensors = [\n sparse_tensor.SparseTensor(ix, val, shape) for (ix, val, shape)\n in zip(context_sparse_indices,\n context_sparse_values,\n context_sparse_shapes)]\n\n feature_list_sparse_tensors = [\n sparse_tensor.SparseTensor(ix, val, shape) for (ix, val, shape)\n in zip(feature_list_sparse_indices,\n feature_list_sparse_values,\n feature_list_sparse_shapes)]\n\n context_output = dict(\n zip(context_sparse_keys + context_dense_keys,\n context_sparse_tensors + context_dense_values))\n feature_list_output = dict(\n zip(feature_list_sparse_keys + feature_list_dense_keys,\n feature_list_sparse_tensors + feature_list_dense_values))\n\n return (context_output, feature_list_output)\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Library for getting system information during TensorFlow tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shlex\nimport subprocess\nimport tempfile\nimport time\n\nimport tensorflow as tf\n\nfrom tensorflow.core.util import test_log_pb2\nfrom tensorflow.tools.test import system_info_lib\n\n\ndef get_git_commit_sha():\n \"\"\"Get git commit SHA for this build.\n\n Attempt to get the SHA from environment variable GIT_COMMIT, which should\n be available on Jenkins build agents.\n\n Returns:\n SHA hash of the git commit used for the build, if available\n \"\"\"\n\n return os.getenv(\"GIT_COMMIT\")\n\n\ndef process_test_logs(\n name, test_name, test_args, start_time, run_time, log_files):\n \"\"\"Gather test information and put it in a TestResults proto.\n\n Args:\n name: Benchmark target identifier.\n test_name: A unique bazel target, e.g. \"//path/to:test\"\n test_args: A string containing all arguments to run the target with.\n\n start_time: Test starting time (epoch)\n run_time: Wall time that the test ran for\n log_files: Paths to the log files\n\n Returns:\n A TestResults proto\n \"\"\"\n\n results = test_log_pb2.TestResults()\n results.name = name\n results.target = test_name\n results.start_time = start_time\n results.run_time = run_time\n\n # Gather source code information\n git_sha = get_git_commit_sha()\n if git_sha:\n results.commit_id.hash = git_sha\n\n results.entries.CopyFrom(process_benchmarks(log_files))\n results.run_configuration.argument.extend(test_args)\n results.machine_configuration.CopyFrom(\n system_info_lib.gather_machine_configuration())\n return results\n\n\ndef process_benchmarks(log_files):\n benchmarks = test_log_pb2.BenchmarkEntries()\n for f in log_files:\n content = tf.gfile.GFile(f, \"rb\").read()\n if benchmarks.MergeFromString(content) != len(content):\n raise Exception(\"Failed parsing benchmark entry from %s\" % f)\n return benchmarks\n\n\ndef run_and_gather_logs(name, test_name, test_args):\n \"\"\"Run the bazel test given by test_name. Gather and return the logs.\n\n Args:\n name: Benchmark target identifier.\n test_name: A unique bazel target, e.g. \"//path/to:test\"\n test_args: A string containing all arguments to run the target with.\n\n Returns:\n A tuple (test_results, mangled_test_name), where\n test_results: A test_log_pb2.TestResults proto\n mangled_test_name: A string, the mangled test name.\n\n Raises:\n ValueError: If the test_name is not a valid target.\n subprocess.CalledProcessError: If the target itself fails.\n IOError: If there are problems gathering test log output from the test.\n \"\"\"\n if not (test_name\n and test_name.startswith(\"//\")\n and \"..\" not in test_name\n and not test_name.endswith(\":\")\n and not test_name.endswith(\":all\")\n and not test_name.endswith(\"...\")\n and len(test_name.split(\":\")) == 2):\n raise ValueError(\"Expected test_name parameter with a unique test, e.g.: \"\n \"--test_name=//path/to:test\")\n test_executable = test_name.rstrip().strip(\"/\").replace(\":\", \"/\")\n\n if tf.gfile.Exists(os.path.join(\"bazel-bin\", test_executable)):\n # Running in standalone mode from core of the repository\n test_executable = os.path.join(\"bazel-bin\", test_executable)\n else:\n # Hopefully running in sandboxed mode\n test_executable = os.path.join(\".\", test_executable)\n\n temp_directory = tempfile.mkdtemp(prefix=\"run_and_gather_logs\")\n mangled_test_name = test_name.strip(\"/\").replace(\"/\", \"_\").replace(\":\", \"_\")\n test_file_prefix = os.path.join(temp_directory, mangled_test_name)\n test_file_prefix = \"%s.\" % test_file_prefix\n\n try:\n if not tf.gfile.Exists(test_executable):\n raise ValueError(\"Executable does not exist: %s\" % test_executable)\n test_args = shlex.split(test_args)\n\n # This key is defined in tf/core/util/reporter.h as\n # TestReporter::kTestReporterEnv.\n os.environ[\"TEST_REPORT_FILE_PREFIX\"] = test_file_prefix\n start_time = time.time()\n subprocess.check_call([test_executable] + test_args)\n run_time = time.time() - start_time\n log_files = tf.gfile.Glob(\"{}*\".format(test_file_prefix))\n\n return (process_test_logs(name, test_name, test_args,\n start_time=int(start_time),\n run_time=run_time, log_files=log_files),\n mangled_test_name)\n\n finally:\n try:\n tf.gfile.DeleteRecursively(temp_directory)\n except OSError:\n pass\n", "# 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# ==============================================================================\n\"\"\"Tests for utility functions in handler.py.\n\nWe import and test the utility functions directly because it's easier than\nstarting up a server.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom six.moves import xrange\n\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.tensorboard.backend import handler\n\n\nclass UniformSampleTest(googletest.TestCase):\n\n def testNotEnoughValues(self):\n self.assertEqual(handler._uniform_sample([1, 2, 3], 10), [1, 2, 3])\n\n def includesProperNumberOfValues(self):\n values = range(10)\n for count in xrange(2, len(values)):\n self.assertEqual(\n len(handler._uniform_sample(values, count)), count,\n 'Sampling %d values from 10 produced the wrong number of values' %\n count)\n\n def testIncludesBeginningAndEnd(self):\n values = range(10)\n for count in xrange(2, len(values)):\n sampled = handler._uniform_sample(values, count)\n self.assertEqual(\n sampled[0], values[0],\n 'Sampling %d values from 10 didn\\'t start with the first value' %\n count)\n self.assertEqual(\n sampled[-1], values[-1],\n 'Sampling %d values from 10 didn\\'t end with the last value' % count)\n\n def testNonIntegerCountFails(self):\n with self.assertRaises(TypeError):\n handler._uniform_sample([1, 2, 3, 4], 3.14159)\n\n with self.assertRaises(TypeError):\n handler._uniform_sample([1, 2, 3, 4], 3.0)\n\n\nif __name__ == '__main__':\n googletest.main()\n", "# Copyright 2016 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\"\"\"Tests for unified pooling functionality in tensorflow.ops.nn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef pool_direct_single_axis(input, # pylint: disable=redefined-builtin\n axis,\n window_size,\n pooling_type,\n padding,\n dilation_rate,\n stride):\n \"\"\"Numpy implementation of pooling along a single axis.\n\n This is intended for testing only, and therefore isn't particularly efficient.\n\n See pool_direct below for the meaning of the arguments.\n\n Args:\n input: numpy array.\n axis: axis along which to perform pooling.\n window_size: int >= 1. Size of pooling window within axis.\n pooling_type: either \"MAX\" or \"AVG\".\n padding: either \"SAME\" or \"VALID\".\n dilation_rate: int >= 1. Dilation factor for window, i.e. stride at which\n to sample input.\n stride: int >= 1. Stride at which to generate output.\n\n Returns:\n pooling output array of rank N+2.\n\n Raises:\n ValueError: if arguments are invalid.\n \"\"\"\n effective_window_size = (window_size - 1) * dilation_rate + 1\n input_size = input.shape[axis]\n if padding == \"SAME\":\n output_size = int(math.ceil(input_size / stride))\n total_padding_amount = max(\n 0, (output_size - 1) * stride + effective_window_size - input_size)\n before_padding = total_padding_amount // 2\n elif padding == \"VALID\":\n output_size = int(\n math.ceil((input_size - effective_window_size + 1) / stride))\n before_padding = 0\n else:\n raise ValueError(\"Unsupported padding type: %r\" % (padding,))\n\n output_shape = input.shape[:axis] + (output_size,) + input.shape[axis + 1:]\n output = np.zeros(output_shape, input.dtype)\n initial_dim_selector = tuple(np.s_[:] for _ in range(axis))\n if pooling_type == \"MAX\":\n pooling_func = np.max\n elif pooling_type == \"AVG\":\n pooling_func = np.mean\n else:\n raise ValueError(\"Unsupported pooling type: %r\" % (pooling_type,))\n for output_pos in range(output_size):\n input_start_pos = output_pos * stride - before_padding\n input_end_pos = min(input_start_pos + effective_window_size, input_size)\n if input_start_pos < 0:\n input_start_pos += dilation_rate\n input_slice = np.s_[input_start_pos:input_end_pos:dilation_rate]\n\n output[initial_dim_selector + (output_pos,)] = pooling_func(\n input[initial_dim_selector + (input_slice,)], axis=axis)\n return output\n\n\ndef pool_direct(input, window_shape, pooling_type, padding, # pylint: disable=redefined-builtin\n dilation_rate, strides, data_format=None):\n \"\"\"Numpy implementation of pooling.\n\n This is intended for testing only, and therefore isn't particularly efficient.\n\n See tensorflow.nn.pool.\n\n Args:\n input: numpy array of rank N+2.\n window_shape: Sequence of N ints >= 1.\n pooling_type: either \"MAX\" or \"AVG\".\n padding: either \"SAME\" or \"VALID\".\n dilation_rate: Sequence of N ints >= 1.\n strides: Sequence of N ints >= 1.\n data_format: If specified and starts with \"NC\", indicates that second\n dimension, rather than the last dimension, specifies the channel.\n\n Returns:\n pooling output array of rank N+2.\n\n Raises:\n ValueError: if arguments are invalid.\n \"\"\"\n if data_format is None or not data_format.startswith(\"NC\"):\n spatial_start_dim = 1\n else:\n spatial_start_dim = 2\n output = input\n for i in range(len(window_shape)):\n output = pool_direct_single_axis(\n input=output,\n axis=i + spatial_start_dim,\n window_size=window_shape[i],\n pooling_type=pooling_type,\n padding=padding,\n dilation_rate=dilation_rate[i],\n stride=strides[i])\n return output\n\n\nclass PoolingTest(tf.test.TestCase):\n\n def _test(self, input_shape, **kwargs):\n # Use negative numbers to make sure there isn't any zero padding getting\n # used.\n x = -np.arange(\n np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1\n y1 = pool_direct(input=x, **kwargs)\n y2 = tf.nn.pool(input=x, **kwargs)\n self.assertAllClose(y1, y2.eval(), rtol=1e-2, atol=1e-2)\n\n def testPoolSimple(self):\n with self.test_session():\n for padding in [\"SAME\", \"VALID\"]:\n for pooling_type in [\"MAX\", \"AVG\"]:\n self._test(\n input_shape=[1, 1, 10, 1],\n window_shape=[1, 3],\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=[1, 1],\n strides=[1, 2])\n\n def testPool1D(self):\n with self.test_session():\n for padding in [\"SAME\", \"VALID\"]:\n for pooling_type in [\"MAX\", \"AVG\"]:\n for input_shape in [[2, 9, 2], [2, 10, 2]]:\n for window_shape in [[1], [2], [3]]:\n if padding != \"SAME\":\n for dilation_rate in [[1], [2], [3]]:\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=dilation_rate,\n strides=[1])\n for strides in [[1], [2], [3]]:\n if np.any(np.array(strides) > window_shape):\n continue\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=[1],\n strides=strides)\n\n def testPool2D(self):\n with self.test_session():\n for padding in [\"SAME\", \"VALID\"]:\n for pooling_type in [\"MAX\", \"AVG\"]:\n for input_shape in [[2, 9, 10, 2], [2, 10, 9, 2]]:\n for window_shape in [[1, 1], [2, 1], [2, 3]]:\n if padding != \"SAME\":\n for dilation_rate in [[1, 1], [2, 1], [1, 2], [2, 3]]:\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=dilation_rate,\n strides=[1, 1])\n for strides in [[1, 1], [2, 1], [1, 2], [2, 3]]:\n if np.any(np.array(strides) > window_shape):\n continue\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=[1, 1],\n strides=strides)\n\n def testPool3D(self):\n with self.test_session():\n for padding in [\"SAME\", \"VALID\"]:\n for pooling_type in [\"MAX\", \"AVG\"]:\n for input_shape in [[2, 9, 10, 11, 2], [2, 10, 9, 11, 2]]:\n for window_shape in [[1, 1, 1], [2, 1, 2], [2, 3, 2]]:\n if padding != \"SAME\":\n for dilation_rate in [[1, 1, 1], [2, 1, 2], [1, 2, 2],\n [2, 3, 3]]:\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=dilation_rate,\n strides=[1, 1, 1])\n for strides in [[1, 1, 1], [2, 1, 2], [1, 2, 2], [2, 3, 3]]:\n if np.any(np.array(strides) > window_shape):\n continue\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=[1, 1, 1],\n strides=strides)\n\n def testPoolNC(self):\n if tf.test.is_gpu_available(cuda_only=True):\n # \"NC*\" format is currently only supported on CUDA.\n with self.test_session(use_gpu=True):\n for padding in [\"SAME\", \"VALID\"]:\n self._test(input_shape=[2, 2, 9],\n window_shape=[2],\n padding=padding,\n pooling_type=\"MAX\",\n strides=[1],\n dilation_rate=[1],\n data_format=\"NCW\")\n self._test(input_shape=[2, 2, 9],\n window_shape=[2],\n padding=padding,\n pooling_type=\"MAX\",\n strides=[2],\n dilation_rate=[1],\n data_format=\"NCW\")\n self._test(input_shape=[2, 2, 7, 9],\n window_shape=[2, 2],\n padding=padding,\n pooling_type=\"MAX\",\n strides=[1, 2],\n dilation_rate=[1, 1],\n data_format=\"NCHW\")\n self._test(input_shape=[2, 2, 7, 9],\n window_shape=[2, 2],\n padding=\"VALID\",\n pooling_type=\"MAX\",\n strides=[1, 1],\n dilation_rate=[2, 2],\n data_format=\"NCHW\")\n\n def _test_gradient(self, input_shape, **kwargs):\n x_val = -np.arange(\n np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1\n x = tf.constant(x_val, name=\"x\", dtype=tf.float32)\n output = tf.nn.pool(input=x, **kwargs)\n y_shape = output.get_shape().as_list()\n err = tf.test.compute_gradient_error(\n [x], [input_shape], output, y_shape, x_init_value=[x_val]\n )\n err_tolerance = 1e-2\n self.assertLess(err, err_tolerance)\n\n def testGradient1D(self):\n with self.test_session():\n for padding in [\"SAME\", \"VALID\"]:\n for pooling_type in [\"AVG\", \"MAX\"]:\n for input_shape in [[2, 5, 2], [1, 4, 1]]:\n for window_shape in [[1], [2]]:\n if padding != \"SAME\":\n for dilation_rate in [[1], [2]]:\n self._test_gradient(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=dilation_rate,\n strides=[1])\n for strides in [[1], [2]]:\n if np.any(np.array(strides) > window_shape):\n continue\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=[1],\n strides=strides)\n\n def testGradient2D(self):\n with self.test_session():\n for padding in [\"SAME\", \"VALID\"]:\n for pooling_type in [\"AVG\", \"MAX\"]:\n for input_shape in [[2, 4, 5, 2], [1, 5, 4, 1]]:\n for window_shape in [[1, 1], [2, 1], [2, 2]]:\n if padding != \"SAME\":\n for dilation_rate in [[1, 1], [2, 1], [2, 2]]:\n self._test_gradient(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=dilation_rate,\n strides=[1, 1])\n for strides in [[1, 1], [2, 1], [1, 2], [2, 2]]:\n if np.any(np.array(strides) > window_shape):\n continue\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=[1, 1],\n strides=strides)\n\n def testGradient3D(self):\n with self.test_session():\n for padding in [\"SAME\", \"VALID\"]:\n for pooling_type in [\"AVG\", \"MAX\"]:\n for input_shape in [[1, 3, 5, 4, 1], [1, 5, 4, 3, 1]]:\n for window_shape in [[1, 1, 1], [2, 1, 2], [2, 2, 2]]:\n if padding != \"SAME\":\n for dilation_rate in [[1, 1, 1], [2, 1, 2], [2, 2, 2]]:\n self._test_gradient(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=dilation_rate,\n strides=[1, 1, 1])\n for strides in [[1, 1, 1], [2, 1, 2], [2, 2, 2]]:\n if np.any(np.array(strides) > window_shape):\n continue\n self._test(\n input_shape=input_shape,\n window_shape=window_shape,\n padding=padding,\n pooling_type=pooling_type,\n dilation_rate=[1, 1, 1],\n strides=strides)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2016 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\"\"\"The RelaxedBernoulli distribution class.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.distributions.python.ops import bijector\nfrom tensorflow.contrib.distributions.python.ops import distribution_util\nfrom tensorflow.contrib.distributions.python.ops import logistic\nfrom tensorflow.contrib.distributions.python.ops import transformed_distribution\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import math_ops\n\n\nclass _RelaxedBernoulli(transformed_distribution.TransformedDistribution):\n \"\"\"RelaxedBernoulli distribution with temperature and logits parameters.\n\n The RelaxedBernoulli is a distribution over the unit interval (0,1), which\n continuously approximates a Bernoulli. The degree of approximation is\n controlled by a temperature: as the temperaturegoes to 0 the RelaxedBernoulli\n becomes discrete with a distribution described by the `logits` or `p`\n parameters, as the temperature goes to infinity the RelaxedBernoulli\n becomes the constant distribution that is identically 0.5.\n\n The RelaxedBernoulli distribution is a reparameterized continuous\n distribution that is the binary special case of the RelaxedOneHotCategorical\n distribution (Maddison et al., 2016; Jang et al., 2016). For details on the\n binary special case see the appendix of Maddison et al. (2016) where it is\n referred to as BinConcrete. If you use this distribution, please cite both\n papers.\n\n Some care needs to be taken for loss functions that depend on the\n log-probability of RelaxedBernoullis, because computing log-probabilities of\n the RelaxedBernoulli can suffer from underflow issues. In many case loss\n functions such as these are invariant under invertible transformations of\n the random variables. The KL divergence, found in the variational autoencoder\n loss, is an example. Because RelaxedBernoullis are sampled by by a Logistic\n random variable followed by a `tf.sigmoid` op, one solution is to treat\n the Logistic as the random variable and `tf.sigmoid` as downstream. The\n KL divergences of two Logistics, which are always followed by a `tf.sigmoid`\n op, is equivalent to evaluating KL divergences of RelaxedBernoulli samples.\n See Maddison et al., 2016 for more details where this distribution is called\n the BinConcrete.\n\n #### Examples\n\n Creates three continuous distributions, which approximate 3 Bernoullis with\n probabilities (0.1, 0.5, 0.4). Samples from these distributions will be in\n the unit interval (0,1).\n\n ```python\n temperature = 0.5\n p = [0.1, 0.5, 0.4]\n dist = RelaxedBernoulli(temperature, p=p)\n ```\n\n Creates three continuous distributions, which approximate 3 Bernoullis with\n logits (-2, 2, 0). Samples from these distributions will be in\n the unit interval (0,1).\n\n ```python\n temperature = 0.5\n logits = [-2, 2, 0]\n dist = RelaxedBernoulli(temperature, logits=logits)\n ```\n\n Creates three continuous distributions, whose sigmoid approximate 3 Bernoullis\n with logits (-2, 2, 0).\n\n ```python\n temperature = 0.5\n logits = [-2, 2, 0]\n dist = Logistic(logits/temperature, 1./temperature)\n samples = dist.sample()\n sigmoid_samples = tf.sigmoid(samples)\n # sigmoid_samples has the same distribution as samples from\n # RelaxedBernoulli(temperature, logits=logits)\n ```\n\n Creates three continuous distributions, which approximate 3 Bernoullis with\n logits (-2, 2, 0). Samples from these distributions will be in\n the unit interval (0,1). Because the temperature is very low, samples from\n these distributions are almost discrete, usually taking values very close to 0\n or 1.\n\n ```python\n temperature = 1e-5\n logits = [-2, 2, 0]\n dist = RelaxedBernoulli(temperature, logits=logits)\n ```\n\n Creates three continuous distributions, which approximate 3 Bernoullis with\n logits (-2, 2, 0). Samples from these distributions will be in\n the unit interval (0,1). Because the temperature is very high, samples from\n these distributions are usually close to the (0.5, 0.5, 0.5) vector.\n\n ```python\n temperature = 100\n logits = [-2, 2, 0]\n dist = RelaxedBernoulli(temperature, logits=logits)\n ```\n\n Chris J. Maddison, Andriy Mnih, and Yee Whye Teh. The Concrete Distribution:\n A Continuous Relaxation of Discrete Random Variables. 2016.\n\n Eric Jang, Shixiang Gu, and Ben Poole. Categorical Reparameterization with\n Gumbel-Softmax. 2016.\n \"\"\"\n\n def __init__(self,\n temperature,\n logits=None,\n p=None,\n validate_args=False,\n allow_nan_stats=True,\n name=\"RelaxedBernoulli\"):\n \"\"\"Construct RelaxedBernoulli distributions.\n\n Args:\n temperature: An 0-D `Tensor`, representing the temperature\n of a set of RelaxedBernoulli distributions. The temperature should be\n positive.\n logits: An N-D `Tensor` representing the log-odds\n of a positive event. Each entry in the `Tensor` parametrizes\n an independent RelaxedBernoulli distribution where the probability of an\n event is sigmoid(logits). Only one of `logits` or `p` should be passed\n in.\n p: An N-D `Tensor` representing the probability of a positive\n event. Each entry in the `Tensor` parameterizes an independent\n Bernoulli distribution. Only one of `logits` or `p` should be passed\n in.\n validate_args: `Boolean`, default `False`. Whether to validate that\n `0 <= p <= 1`. If `validate_args` is `False`, and the inputs are\n invalid, methods like `log_pmf` may return `NaN` values.\n allow_nan_stats: `Boolean`, default `True`. If `False`, raise an\n exception if a statistic (e.g. mean/mode/etc...) is undefined for any\n batch member. If `True`, batch members with valid parameters leading to\n undefined statistics will return NaN for this statistic.\n name: A name for this distribution.\n\n Raises:\n ValueError: If p and logits are passed, or if neither are passed.\n \"\"\"\n parameters = locals()\n parameters.pop(\"self\")\n with ops.name_scope(name, values=[logits, p, temperature]) as ns:\n with ops.control_dependencies([check_ops.assert_positive(temperature)]\n if validate_args else []):\n self._temperature = array_ops.identity(temperature, name=\"temperature\")\n\n self._logits, self._p = distribution_util.get_logits_and_prob(\n logits=logits, p=p, validate_args=validate_args)\n with ops.name_scope(\"q\"):\n self._q = 1. - self._p\n dist = logistic._Logistic(self._logits / self._temperature,\n 1./self._temperature,\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n name=ns)\n\n def inverse_log_det_jacobian_fn(y):\n return -math_ops.reduce_sum(math_ops.log(y) + math_ops.log(1-y),\n reduction_indices=-1)\n\n sigmoidbijector = bijector.Inline(\n forward_fn=math_ops.sigmoid,\n inverse_fn=(lambda y: math_ops.log(y) - math_ops.log(1-y)),\n inverse_log_det_jacobian_fn=inverse_log_det_jacobian_fn,\n name=\"sigmoid\")\n super(_RelaxedBernoulli, self).__init__(dist,\n sigmoidbijector,\n name=name)\n\n @staticmethod\n def _param_shapes(sample_shape):\n return {\"logits\": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)}\n\n @property\n def temperature(self):\n \"\"\"Distribution parameter for the location.\"\"\"\n return self._temperature\n\n @property\n def logits(self):\n \"\"\"Log-odds of success.\"\"\"\n return self._logits\n\n @property\n def p(self):\n \"\"\"Probability of success.\"\"\"\n return self._p\n\n @property\n def q(self):\n \"\"\"Probability of failure.\"\"\"\n return self._q\n", "# 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# ==============================================================================\n\n\"\"\"Contains the implementation for the DirectoryWatcher class.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport bisect\n\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.summary.impl import io_wrapper\n\n\nclass DirectoryWatcher(object):\n \"\"\"A DirectoryWatcher wraps a loader to load from a sequence of paths.\n\n A loader reads a path and produces some kind of values as an iterator. A\n DirectoryWatcher takes a directory, a factory for loaders, and optionally a\n path filter and watches all the paths inside that directory.\n\n This class is only valid under the assumption that only one path will be\n written to by the data source at a time and that once the source stops writing\n to a path, it will start writing to a new path that's lexicographically\n greater and never come back. It uses some heuristics to check whether this is\n true based on tracking changes to the files' sizes, but the check can have\n false negatives. However, it should have no false positives.\n \"\"\"\n\n def __init__(self, directory, loader_factory, path_filter=lambda x: True):\n \"\"\"Constructs a new DirectoryWatcher.\n\n Args:\n directory: The directory to load files from.\n loader_factory: A factory for creating loaders. The factory should take a\n path and return an object that has a Load method returning an\n iterator that will yield all events that have not been yielded yet.\n path_filter: If specified, only paths matching this filter are loaded.\n\n Raises:\n ValueError: If path_provider or loader_factory are None.\n \"\"\"\n if directory is None:\n raise ValueError('A directory is required')\n if loader_factory is None:\n raise ValueError('A loader factory is required')\n self._directory = directory\n self._path = None\n self._loader_factory = loader_factory\n self._loader = None\n self._path_filter = path_filter\n self._ooo_writes_detected = False\n # The file size for each file at the time it was finalized.\n self._finalized_sizes = {}\n\n def Load(self):\n \"\"\"Loads new values.\n\n The watcher will load from one path at a time; as soon as that path stops\n yielding events, it will move on to the next path. We assume that old paths\n are never modified after a newer path has been written. As a result, Load()\n can be called multiple times in a row without losing events that have not\n been yielded yet. In other words, we guarantee that every event will be\n yielded exactly once.\n\n Yields:\n All values that have not been yielded yet.\n\n Raises:\n DirectoryDeletedError: If the directory has been permanently deleted\n (as opposed to being temporarily unavailable).\n \"\"\"\n try:\n for event in self._LoadInternal():\n yield event\n except errors.OpError:\n if not gfile.Exists(self._directory):\n raise DirectoryDeletedError(\n 'Directory %s has been permanently deleted' % self._directory)\n\n def _LoadInternal(self):\n \"\"\"Internal implementation of Load().\n\n The only difference between this and Load() is that the latter will throw\n DirectoryDeletedError on I/O errors if it thinks that the directory has been\n permanently deleted.\n\n Yields:\n All values that have not been yielded yet.\n \"\"\"\n\n # If the loader exists, check it for a value.\n if not self._loader:\n self._InitializeLoader()\n\n while True:\n # Yield all the new events in the path we're currently loading from.\n for event in self._loader.Load():\n yield event\n\n next_path = self._GetNextPath()\n if not next_path:\n logging.info('No path found after %s', self._path)\n # Current path is empty and there are no new paths, so we're done.\n return\n\n # There's a new path, so check to make sure there weren't any events\n # written between when we finished reading the current path and when we\n # checked for the new one. The sequence of events might look something\n # like this:\n #\n # 1. Event #1 written to path #1.\n # 2. We check for events and yield event #1 from path #1\n # 3. We check for events and see that there are no more events in path #1.\n # 4. Event #2 is written to path #1.\n # 5. Event #3 is written to path #2.\n # 6. We check for a new path and see that path #2 exists.\n #\n # Without this loop, we would miss event #2. We're also guaranteed by the\n # loader contract that no more events will be written to path #1 after\n # events start being written to path #2, so we don't have to worry about\n # that.\n for event in self._loader.Load():\n yield event\n\n logging.info('Directory watcher advancing from %s to %s', self._path,\n next_path)\n\n # Advance to the next path and start over.\n self._SetPath(next_path)\n\n # The number of paths before the current one to check for out of order writes.\n _OOO_WRITE_CHECK_COUNT = 20\n\n def OutOfOrderWritesDetected(self):\n \"\"\"Returns whether any out-of-order writes have been detected.\n\n Out-of-order writes are only checked as part of the Load() iterator. Once an\n out-of-order write is detected, this function will always return true.\n\n Note that out-of-order write detection is not performed on GCS paths, so\n this function will always return false.\n\n Returns:\n Whether any out-of-order write has ever been detected by this watcher.\n\n \"\"\"\n return self._ooo_writes_detected\n\n def _InitializeLoader(self):\n path = self._GetNextPath()\n if path:\n self._SetPath(path)\n else:\n raise StopIteration\n\n def _SetPath(self, path):\n \"\"\"Sets the current path to watch for new events.\n\n This also records the size of the old path, if any. If the size can't be\n found, an error is logged.\n\n Args:\n path: The full path of the file to watch.\n \"\"\"\n old_path = self._path\n if old_path and not io_wrapper.IsGCSPath(old_path):\n try:\n # We're done with the path, so store its size.\n size = gfile.Stat(old_path).length\n logging.debug('Setting latest size of %s to %d', old_path, size)\n self._finalized_sizes[old_path] = size\n except errors.OpError as e:\n logging.error('Unable to get size of %s: %s', old_path, e)\n\n self._path = path\n self._loader = self._loader_factory(path)\n\n def _GetNextPath(self):\n \"\"\"Gets the next path to load from.\n\n This function also does the checking for out-of-order writes as it iterates\n through the paths.\n\n Returns:\n The next path to load events from, or None if there are no more paths.\n \"\"\"\n paths = sorted(path\n for path in io_wrapper.ListDirectoryAbsolute(self._directory)\n if self._path_filter(path))\n if not paths:\n return None\n\n if self._path is None:\n return paths[0]\n\n # Don't bother checking if the paths are GCS (which we can't check) or if\n # we've already detected an OOO write.\n if not io_wrapper.IsGCSPath(paths[0]) and not self._ooo_writes_detected:\n # Check the previous _OOO_WRITE_CHECK_COUNT paths for out of order writes.\n current_path_index = bisect.bisect_left(paths, self._path)\n ooo_check_start = max(0, current_path_index - self._OOO_WRITE_CHECK_COUNT)\n for path in paths[ooo_check_start:current_path_index]:\n if self._HasOOOWrite(path):\n self._ooo_writes_detected = True\n break\n\n next_paths = list(path\n for path in paths\n if self._path is None or path > self._path)\n if next_paths:\n return min(next_paths)\n else:\n return None\n\n def _HasOOOWrite(self, path):\n \"\"\"Returns whether the path has had an out-of-order write.\"\"\"\n # Check the sizes of each path before the current one.\n size = gfile.Stat(path).length\n old_size = self._finalized_sizes.get(path, None)\n if size != old_size:\n if old_size is None:\n logging.error('File %s created after file %s even though it\\'s '\n 'lexicographically earlier', path, self._path)\n else:\n logging.error('File %s updated even though the current file is %s',\n path, self._path)\n return True\n else:\n return False\n\n\nclass DirectoryDeletedError(Exception):\n \"\"\"Thrown by Load() when the directory is *permanently* gone.\n\n We distinguish this from temporary errors so that other code can decide to\n drop all of our data only when a directory has been intentionally deleted,\n as opposed to due to transient filesystem errors.\n \"\"\"\n pass\n", "# Copyright 2016 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\"\"\"Tests for TaskRunner and Experiment class.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport tempfile\nimport threading\n\nimport tensorflow as tf\n\nfrom tensorflow.contrib.learn.python.learn import run_config\nfrom tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util.all_util import reveal_undocumented\n\npatch = tf.test.mock.patch\n\n\nclass SheepCounter(object):\n \"\"\"To be patched in for time.sleep, in order to capture how long was slept.\"\"\"\n\n def __init__(self):\n self._total_time = 0\n self._sleeptimes = []\n\n def __call__(self, t):\n self._total_time += t\n self._sleeptimes += [t]\n\n @property\n def total_time(self):\n return self._total_time\n\n @property\n def sleep_times(self):\n return self._sleeptimes\n\n\nclass TestEstimator(tf.contrib.learn.Evaluable, tf.contrib.learn.Trainable):\n\n def __init__(self, config=None, max_evals=5):\n self.eval_count = 0\n self.fit_count = 0\n self._max_evals = max_evals\n self.export_count = 0\n self.monitors = []\n self._config = config or run_config.RunConfig()\n self._model_dir = tempfile.mkdtemp()\n\n @property\n def model_dir(self):\n return self._model_dir\n\n @property\n def config(self):\n return self._config\n\n def evaluate(self, **kwargs):\n tf.logging.info('evaluate called with args: %s' % kwargs)\n self.eval_count += 1\n if self.eval_count > self._max_evals:\n tf.logging.info('Ran %d evals. Done.' % self.eval_count)\n raise StopIteration()\n return [(key, kwargs[key]) for key in sorted(kwargs.keys())]\n\n def fake_checkpoint(self):\n save_path = os.path.join(self.model_dir, 'model.ckpt')\n with tf.Session() as sess:\n var = tf.Variable(1.0, name='var0')\n save = tf.train.Saver({var.op.name: var})\n var.initializer.run()\n save.save(sess, save_path, global_step=0)\n\n def fit(self, **kwargs):\n self.fake_checkpoint()\n tf.logging.info('fit called with args: %s' % kwargs)\n self.fit_count += 1\n if 'monitors' in kwargs:\n self.monitors = kwargs['monitors']\n return [(key, kwargs[key]) for key in sorted(kwargs.keys())]\n\n def export_savedmodel(self, export_dir_base, export_input_fn, **kwargs):\n tf.logging.info('export_savedmodel called with args: %s, %s, %s'\n % (export_dir_base, export_input_fn, kwargs))\n self.export_count += 1\n return os.path.join(compat.as_bytes(export_dir_base),\n compat.as_bytes('bogus_timestamp'))\n\n\nclass ExperimentTest(tf.test.TestCase):\n\n def setUp(self):\n # The official name is tf.train, so tf.training was obliterated.\n reveal_undocumented('tensorflow.python.training')\n\n def _cluster_spec(self):\n return {\n tf.contrib.learn.TaskType.PS: ['host1:2222', 'host2:2222'],\n tf.contrib.learn.TaskType.WORKER:\n ['host3:2222', 'host4:2222', 'host5:2222']\n }\n\n def test_train(self):\n est = TestEstimator()\n ex = tf.contrib.learn.Experiment(\n est,\n train_input_fn='train_input',\n train_steps='train_steps',\n eval_input_fn='eval_input',\n eval_metrics='eval_metrics')\n fit_args = ex.train(delay_secs=0)\n self.assertEquals(1, est.fit_count)\n self.assertIn(('max_steps', 'train_steps'), fit_args)\n self.assertEquals(0, est.eval_count)\n\n def test_train_delay(self):\n est = TestEstimator()\n ex = tf.contrib.learn.Experiment(\n est, train_input_fn='train_input', eval_input_fn='eval_input')\n for delay in [0, 1, 3]:\n with patch('time.sleep', SheepCounter()) as sheep:\n ex.train(delay_secs=delay)\n self.assertAlmostEqual(delay, sheep.total_time, delta=0.1)\n\n def test_train_default_delay(self):\n for task_id in [0, 1, 3]:\n tf_config = {'task': {'index': task_id}}\n with patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}):\n config = run_config.RunConfig()\n est = TestEstimator(config)\n ex = tf.contrib.learn.Experiment(\n est, train_input_fn='train_input', eval_input_fn='eval_input')\n\n with patch('time.sleep', SheepCounter()) as sheep:\n ex.train()\n self.assertAlmostEqual(task_id * 5, sheep.total_time, delta=0.1)\n\n @tf.test.mock.patch('tensorflow.python.training.server_lib.Server') # pylint: disable=line-too-long\n def test_train_starts_server(self, mock_server):\n # Arrange.\n tf_config = {\n 'cluster': self._cluster_spec(),\n 'environment': tf.contrib.learn.Environment.CLOUD,\n 'task': {\n 'type': tf.contrib.learn.TaskType.WORKER,\n 'index': 1\n }\n }\n with patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}):\n config = tf.contrib.learn.RunConfig(\n master='host4:2222', num_cores=15, gpu_memory_fraction=0.314)\n\n est = TestEstimator(config)\n ex = tf.contrib.learn.Experiment(\n est, train_input_fn='train_input', eval_input_fn='eval_input')\n\n # Act.\n # We want to make sure we discount the time it takes to start the server\n # in our accounting of the delay, so we set a small delay here.\n with patch('time.sleep', SheepCounter()) as sheep:\n ex.train(delay_secs=1)\n # Ensure that the delay takes into account the time to start the server.\n self.assertAlmostEqual(1, sheep.total_time, delta=0.1)\n\n # Assert.\n expected_config_proto = tf.ConfigProto()\n expected_config_proto.inter_op_parallelism_threads = 15\n expected_config_proto.intra_op_parallelism_threads = 15\n expected_config_proto.gpu_options.per_process_gpu_memory_fraction = 0.314\n mock_server.assert_called_with(\n config.cluster_spec,\n job_name=tf.contrib.learn.TaskType.WORKER,\n task_index=1,\n config=expected_config_proto,\n start=False)\n mock_server.assert_has_calls([tf.test.mock.call().start()])\n\n @tf.test.mock.patch('tensorflow.python.training.server_lib.Server') # pylint: disable=line-too-long\n def test_train_server_does_not_start_without_cluster_spec(self, mock_server):\n config = tf.contrib.learn.RunConfig(master='host4:2222')\n ex = tf.contrib.learn.Experiment(\n TestEstimator(config),\n train_input_fn='train_input',\n eval_input_fn='eval_input')\n ex.train()\n\n # The server should not have started because there was no ClusterSpec.\n self.assertFalse(mock_server.called)\n\n @tf.test.mock.patch('tensorflow.python.training.server_lib.Server') # pylint: disable=line-too-long\n def test_train_server_does_not_start_with_empty_master(self, mock_server):\n tf_config = {'cluster': self._cluster_spec()}\n with patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}):\n config = tf.contrib.learn.RunConfig(master='')\n ex = tf.contrib.learn.Experiment(\n TestEstimator(config),\n train_input_fn='train_input',\n eval_input_fn='eval_input')\n ex.train()\n\n # The server should not have started because master was the empty string.\n self.assertFalse(mock_server.called)\n\n def test_train_raises_if_job_name_is_missing(self):\n tf_config = {\n 'cluster': self._cluster_spec(),\n 'environment': tf.contrib.learn.Environment.CLOUD,\n 'task': {\n 'index': 1\n }\n }\n with patch.dict(\n 'os.environ',\n {'TF_CONFIG': json.dumps(tf_config)}), self.assertRaises(ValueError):\n config = tf.contrib.learn.RunConfig(\n master='host3:2222' # Normally selected by task type.\n )\n ex = tf.contrib.learn.Experiment(\n TestEstimator(config),\n train_input_fn='train_input',\n eval_input_fn='eval_input')\n ex.train()\n\n def test_evaluate(self):\n est = TestEstimator()\n est.fake_checkpoint()\n ex = tf.contrib.learn.Experiment(\n est,\n train_input_fn='train_input',\n eval_input_fn='eval_input',\n eval_metrics='eval_metrics',\n eval_steps='steps',\n eval_delay_secs=0)\n ex.evaluate()\n self.assertEquals(1, est.eval_count)\n self.assertEquals(0, est.fit_count)\n\n def test_evaluate_delay(self):\n est = TestEstimator()\n est.fake_checkpoint()\n ex = tf.contrib.learn.Experiment(\n est, train_input_fn='train_input', eval_input_fn='eval_input')\n\n for delay in [0, 1, 3]:\n with patch('time.sleep', SheepCounter()) as sheep:\n ex.evaluate(delay_secs=delay)\n self.assertAlmostEqual(delay, sheep.total_time, delta=0.1)\n\n def test_continuous_eval(self):\n est = TestEstimator()\n est.fake_checkpoint()\n ex = tf.contrib.learn.Experiment(\n est,\n train_input_fn='train_input',\n eval_input_fn='eval_input',\n eval_metrics='eval_metrics',\n eval_delay_secs=0,\n continuous_eval_throttle_secs=0)\n self.assertRaises(StopIteration, ex.continuous_eval,\n evaluate_checkpoint_only_once=False)\n self.assertEquals(6, est.eval_count)\n self.assertEquals(0, est.fit_count)\n\n def test_continuous_eval_throttle_delay(self):\n for delay in [0, 1, 2]:\n est = TestEstimator()\n est.fake_checkpoint()\n ex = tf.contrib.learn.Experiment(\n est,\n train_input_fn='train_input',\n eval_input_fn='eval_input',\n eval_metrics='eval_metrics',\n continuous_eval_throttle_secs=delay,\n eval_delay_secs=0)\n with patch('time.sleep', SheepCounter()) as sheep:\n self.assertRaises(StopIteration, ex.continuous_eval,\n evaluate_checkpoint_only_once=False)\n self.assertAlmostEqual(5 * delay, sheep.total_time, delta=0.1)\n\n def test_run_local(self):\n est = TestEstimator()\n ex = tf.contrib.learn.Experiment(\n est,\n train_input_fn='train_input',\n eval_input_fn='eval_input',\n eval_metrics='eval_metrics',\n train_steps=100,\n eval_steps=100,\n local_eval_frequency=10)\n ex.local_run()\n self.assertEquals(1, est.fit_count)\n self.assertEquals(1, est.eval_count)\n self.assertEquals(1, len(est.monitors))\n self.assertTrue(\n isinstance(est.monitors[0],\n tf.contrib.learn.monitors.ValidationMonitor))\n\n def test_train_and_evaluate(self):\n est = TestEstimator()\n export_strategy = saved_model_export_utils.make_export_strategy(\n est, 'export_input')\n ex = tf.contrib.learn.Experiment(\n est,\n train_input_fn='train_input',\n eval_input_fn='eval_input',\n eval_metrics='eval_metrics',\n train_steps=100,\n eval_steps=100,\n export_strategies=export_strategy)\n ex.train_and_evaluate()\n self.assertEquals(1, est.fit_count)\n self.assertEquals(1, est.eval_count)\n self.assertEquals(1, est.export_count)\n self.assertEquals(1, len(est.monitors))\n self.assertTrue(\n isinstance(est.monitors[0],\n tf.contrib.learn.monitors.ValidationMonitor))\n\n @tf.test.mock.patch('tensorflow.python.training.server_lib.Server') # pylint: disable=line-too-long\n def test_run_std_server(self, mock_server):\n # Arrange.\n tf_config = {\n 'cluster': self._cluster_spec(),\n 'task': {\n 'type': tf.contrib.learn.TaskType.PS,\n 'index': 1\n }\n }\n with patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}):\n config = tf.contrib.learn.RunConfig(\n master='host2:2222',\n num_cores=15,\n gpu_memory_fraction=0.314,)\n est = TestEstimator(config)\n ex = tf.contrib.learn.Experiment(\n est, train_input_fn='train_input', eval_input_fn='eval_input')\n\n # Act.\n ex.run_std_server()\n\n # Assert.\n mock_server.assert_has_calls(\n [tf.test.mock.call().start(), tf.test.mock.call().join()])\n\n @tf.test.mock.patch('tensorflow.python.training.server_lib.Server') # pylint: disable=line-too-long\n def test_run_std_server_raises_without_cluster_spec(self, mock_server):\n config = tf.contrib.learn.RunConfig(master='host4:2222')\n with self.assertRaises(ValueError):\n ex = tf.contrib.learn.Experiment(\n TestEstimator(config),\n train_input_fn='train_input',\n eval_input_fn='eval_input')\n ex.run_std_server()\n\n def test_test(self):\n est = TestEstimator()\n ex = tf.contrib.learn.Experiment(\n est, train_input_fn='train_input', eval_input_fn='eval_input')\n ex.test()\n self.assertEquals(1, est.fit_count)\n self.assertEquals(1, est.eval_count)\n\n def test_continuous_eval_evaluates_checkpoint_once(self):\n # Temporarily disabled until we figure out the threading story on Jenkins.\n return\n # pylint: disable=unreachable\n\n # The TestEstimator will raise StopIteration the second time evaluate is\n # called.\n ex = tf.contrib.learn.Experiment(\n TestEstimator(max_evals=1),\n train_input_fn='train_input',\n eval_input_fn='eval_input')\n\n # This should not happen if the logic restricting evaluation of the same\n # checkpoint works. We do need some checkpoint though, otherwise Experiment\n # will never evaluate.\n ex.estimator.fake_checkpoint()\n\n # Start a separate thread with continuous eval\n thread = threading.Thread(\n target=lambda: ex.continuous_eval(delay_secs=0, throttle_delay_secs=0))\n thread.start()\n\n # The thread will die if it evaluates twice, and we should never evaluate\n # twice since we don't write another checkpoint. Since we did not enable\n # throttling, if it hasn't died after two seconds, we're good.\n thread.join(2)\n self.assertTrue(thread.is_alive())\n\n # But we should have evaluated once.\n count = ex.estimator.eval_count\n self.assertEquals(1, count)\n\nif __name__ == '__main__':\n tf.test.main()\n", "# 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# ==============================================================================\n\"\"\"Exception types for TensorFlow errors.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\nimport traceback\nimport warnings\n\nfrom tensorflow.core.lib.core import error_codes_pb2\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.util import compat\n\n\nclass OpError(Exception):\n \"\"\"A generic error that is raised when TensorFlow execution fails.\n\n Whenever possible, the session will raise a more specific subclass\n of `OpError` from the `tf.errors` module.\n\n @@op\n @@node_def\n \"\"\"\n\n def __init__(self, node_def, op, message, error_code):\n \"\"\"Creates a new `OpError` indicating that a particular op failed.\n\n Args:\n node_def: The `node_def_pb2.NodeDef` proto representing the op that\n failed, if known; otherwise None.\n op: The `ops.Operation` that failed, if known; otherwise None.\n message: The message string describing the failure.\n error_code: The `error_codes_pb2.Code` describing the error.\n \"\"\"\n super(OpError, self).__init__()\n self._message = message\n self._node_def = node_def\n self._op = op\n self._error_code = error_code\n\n @property\n def message(self):\n \"\"\"The error message that describes the error.\"\"\"\n return self._message\n\n @property\n def op(self):\n \"\"\"The operation that failed, if known.\n\n *N.B.* If the failed op was synthesized at runtime, e.g. a `Send`\n or `Recv` op, there will be no corresponding\n [`Operation`](../../api_docs/python/framework.md#Operation)\n object. In that case, this will return `None`, and you should\n instead use the [`OpError.node_def`](#OpError.node_def) to\n discover information about the op.\n\n Returns:\n The `Operation` that failed, or None.\n \"\"\"\n return self._op\n\n @property\n def error_code(self):\n \"\"\"The integer error code that describes the error.\"\"\"\n return self._error_code\n\n @property\n def node_def(self):\n \"\"\"The `NodeDef` proto representing the op that failed.\"\"\"\n return self._node_def\n\n def __str__(self):\n if self._op is not None:\n output = [\"%s\\n\\nCaused by op %r, defined at:\\n\" % (self.message,\n self._op.name,)]\n curr_traceback_list = traceback.format_list(self._op.traceback)\n output.extend(curr_traceback_list)\n # pylint: disable=protected-access\n original_op = self._op._original_op\n # pylint: enable=protected-access\n while original_op is not None:\n output.append(\n \"\\n...which was originally created as op %r, defined at:\\n\"\n % (original_op.name,))\n prev_traceback_list = curr_traceback_list\n curr_traceback_list = traceback.format_list(original_op.traceback)\n\n # Attempt to elide large common subsequences of the subsequent\n # stack traces.\n #\n # TODO(mrry): Consider computing the actual longest common subsequence.\n is_eliding = False\n elide_count = 0\n last_elided_line = None\n for line, line_in_prev in zip(curr_traceback_list, prev_traceback_list):\n if line == line_in_prev:\n if is_eliding:\n elide_count += 1\n last_elided_line = line\n else:\n output.append(line)\n is_eliding = True\n elide_count = 0\n else:\n if is_eliding:\n if elide_count > 0:\n output.extend(\n [\"[elided %d identical lines from previous traceback]\\n\"\n % (elide_count - 1,), last_elided_line])\n is_eliding = False\n output.extend(line)\n\n # pylint: disable=protected-access\n original_op = original_op._original_op\n # pylint: enable=protected-access\n output.append(\"\\n%s (see above for traceback): %s\\n\" %\n (type(self).__name__, self.message))\n return \"\".join(output)\n else:\n return self.message\n\n\nOK = error_codes_pb2.OK\nCANCELLED = error_codes_pb2.CANCELLED\nUNKNOWN = error_codes_pb2.UNKNOWN\nINVALID_ARGUMENT = error_codes_pb2.INVALID_ARGUMENT\nDEADLINE_EXCEEDED = error_codes_pb2.DEADLINE_EXCEEDED\nNOT_FOUND = error_codes_pb2.NOT_FOUND\nALREADY_EXISTS = error_codes_pb2.ALREADY_EXISTS\nPERMISSION_DENIED = error_codes_pb2.PERMISSION_DENIED\nUNAUTHENTICATED = error_codes_pb2.UNAUTHENTICATED\nRESOURCE_EXHAUSTED = error_codes_pb2.RESOURCE_EXHAUSTED\nFAILED_PRECONDITION = error_codes_pb2.FAILED_PRECONDITION\nABORTED = error_codes_pb2.ABORTED\nOUT_OF_RANGE = error_codes_pb2.OUT_OF_RANGE\nUNIMPLEMENTED = error_codes_pb2.UNIMPLEMENTED\nINTERNAL = error_codes_pb2.INTERNAL\nUNAVAILABLE = error_codes_pb2.UNAVAILABLE\nDATA_LOSS = error_codes_pb2.DATA_LOSS\n\n\n# pylint: disable=line-too-long\nclass CancelledError(OpError):\n \"\"\"Raised when an operation or step is cancelled.\n\n For example, a long-running operation (e.g.\n [`queue.enqueue()`](../../api_docs/python/io_ops.md#QueueBase.enqueue) may be\n cancelled by running another operation (e.g.\n [`queue.close(cancel_pending_enqueues=True)`](../../api_docs/python/io_ops.md#QueueBase.close),\n or by [closing the session](../../api_docs/python/client.md#Session.close).\n A step that is running such a long-running operation will fail by raising\n `CancelledError`.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates a `CancelledError`.\"\"\"\n super(CancelledError, self).__init__(node_def, op, message, CANCELLED)\n# pylint: enable=line-too-long\n\n\nclass UnknownError(OpError):\n \"\"\"Unknown error.\n\n An example of where this error may be returned is if a Status value\n received from another address space belongs to an error-space that\n is not known to this address space. Also errors raised by APIs that\n do not return enough error information may be converted to this\n error.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message, error_code=UNKNOWN):\n \"\"\"Creates an `UnknownError`.\"\"\"\n super(UnknownError, self).__init__(node_def, op, message, error_code)\n\n\nclass InvalidArgumentError(OpError):\n \"\"\"Raised when an operation receives an invalid argument.\n\n This may occur, for example, if an operation is receives an input\n tensor that has an invalid value or shape. For example, the\n [`tf.matmul()`](../../api_docs/python/math_ops.md#matmul) op will raise this\n error if it receives an input that is not a matrix, and the\n [`tf.reshape()`](../../api_docs/python/array_ops.md#reshape) op will raise\n this error if the new shape does not match the number of elements in the input\n tensor.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `InvalidArgumentError`.\"\"\"\n super(InvalidArgumentError, self).__init__(node_def, op, message,\n INVALID_ARGUMENT)\n\n\nclass DeadlineExceededError(OpError):\n \"\"\"Raised when a deadline expires before an operation could complete.\n\n This exception is not currently used.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates a `DeadlineExceededError`.\"\"\"\n super(DeadlineExceededError, self).__init__(node_def, op, message,\n DEADLINE_EXCEEDED)\n\n\nclass NotFoundError(OpError):\n \"\"\"Raised when a requested entity (e.g., a file or directory) was not found.\n\n For example, running the\n [`tf.WholeFileReader.read()`](../../api_docs/python/io_ops.md#WholeFileReader)\n operation could raise `NotFoundError` if it receives the name of a file that\n does not exist.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates a `NotFoundError`.\"\"\"\n super(NotFoundError, self).__init__(node_def, op, message, NOT_FOUND)\n\n\nclass AlreadyExistsError(OpError):\n \"\"\"Raised when an entity that we attempted to create already exists.\n\n For example, running an operation that saves a file\n (e.g. [`tf.train.Saver.save()`](../../api_docs/python/train.md#Saver.save))\n could potentially raise this exception if an explicit filename for an\n existing file was passed.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `AlreadyExistsError`.\"\"\"\n super(AlreadyExistsError, self).__init__(node_def, op, message,\n ALREADY_EXISTS)\n\n\nclass PermissionDeniedError(OpError):\n \"\"\"Raised when the caller does not have permission to run an operation.\n\n For example, running the\n [`tf.WholeFileReader.read()`](../../api_docs/python/io_ops.md#WholeFileReader)\n operation could raise `PermissionDeniedError` if it receives the name of a\n file for which the user does not have the read file permission.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates a `PermissionDeniedError`.\"\"\"\n super(PermissionDeniedError, self).__init__(node_def, op, message,\n PERMISSION_DENIED)\n\n\nclass UnauthenticatedError(OpError):\n \"\"\"The request does not have valid authentication credentials.\n\n This exception is not currently used.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `UnauthenticatedError`.\"\"\"\n super(UnauthenticatedError, self).__init__(node_def, op, message,\n UNAUTHENTICATED)\n\n\nclass ResourceExhaustedError(OpError):\n \"\"\"Some resource has been exhausted.\n\n For example, this error might be raised if a per-user quota is\n exhausted, or perhaps the entire file system is out of space.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates a `ResourceExhaustedError`.\"\"\"\n super(ResourceExhaustedError, self).__init__(node_def, op, message,\n RESOURCE_EXHAUSTED)\n\n\nclass FailedPreconditionError(OpError):\n \"\"\"Operation was rejected because the system is not in a state to execute it.\n\n This exception is most commonly raised when running an operation\n that reads a [`tf.Variable`](../../api_docs/python/state_ops.md#Variable)\n before it has been initialized.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates a `FailedPreconditionError`.\"\"\"\n super(FailedPreconditionError, self).__init__(node_def, op, message,\n FAILED_PRECONDITION)\n\n\nclass AbortedError(OpError):\n \"\"\"The operation was aborted, typically due to a concurrent action.\n\n For example, running a\n [`queue.enqueue()`](../../api_docs/python/io_ops.md#QueueBase.enqueue)\n operation may raise `AbortedError` if a\n [`queue.close()`](../../api_docs/python/io_ops.md#QueueBase.close) operation\n previously ran.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `AbortedError`.\"\"\"\n super(AbortedError, self).__init__(node_def, op, message, ABORTED)\n\n\nclass OutOfRangeError(OpError):\n \"\"\"Raised when an operation iterates past the valid input range.\n\n This exception is raised in \"end-of-file\" conditions, such as when a\n [`queue.dequeue()`](../../api_docs/python/io_ops.md#QueueBase.dequeue)\n operation is blocked on an empty queue, and a\n [`queue.close()`](../../api_docs/python/io_ops.md#QueueBase.close)\n operation executes.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `OutOfRangeError`.\"\"\"\n super(OutOfRangeError, self).__init__(node_def, op, message,\n OUT_OF_RANGE)\n\n\nclass UnimplementedError(OpError):\n \"\"\"Raised when an operation has not been implemented.\n\n Some operations may raise this error when passed otherwise-valid\n arguments that it does not currently support. For example, running\n the [`tf.nn.max_pool()`](../../api_docs/python/nn.md#max_pool) operation\n would raise this error if pooling was requested on the batch dimension,\n because this is not yet supported.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `UnimplementedError`.\"\"\"\n super(UnimplementedError, self).__init__(node_def, op, message,\n UNIMPLEMENTED)\n\n\nclass InternalError(OpError):\n \"\"\"Raised when the system experiences an internal error.\n\n This exception is raised when some invariant expected by the runtime\n has been broken. Catching this exception is not recommended.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `InternalError`.\"\"\"\n super(InternalError, self).__init__(node_def, op, message, INTERNAL)\n\n\nclass UnavailableError(OpError):\n \"\"\"Raised when the runtime is currently unavailable.\n\n This exception is not currently used.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates an `UnavailableError`.\"\"\"\n super(UnavailableError, self).__init__(node_def, op, message,\n UNAVAILABLE)\n\n\nclass DataLossError(OpError):\n \"\"\"Raised when unrecoverable data loss or corruption is encountered.\n\n For example, this may be raised by running a\n [`tf.WholeFileReader.read()`](../../api_docs/python/io_ops.md#WholeFileReader)\n operation, if the file is truncated while it is being read.\n\n @@__init__\n \"\"\"\n\n def __init__(self, node_def, op, message):\n \"\"\"Creates a `DataLossError`.\"\"\"\n super(DataLossError, self).__init__(node_def, op, message, DATA_LOSS)\n\n\n_CODE_TO_EXCEPTION_CLASS = {\n CANCELLED: CancelledError,\n UNKNOWN: UnknownError,\n INVALID_ARGUMENT: InvalidArgumentError,\n DEADLINE_EXCEEDED: DeadlineExceededError,\n NOT_FOUND: NotFoundError,\n ALREADY_EXISTS: AlreadyExistsError,\n PERMISSION_DENIED: PermissionDeniedError,\n UNAUTHENTICATED: UnauthenticatedError,\n RESOURCE_EXHAUSTED: ResourceExhaustedError,\n FAILED_PRECONDITION: FailedPreconditionError,\n ABORTED: AbortedError,\n OUT_OF_RANGE: OutOfRangeError,\n UNIMPLEMENTED: UnimplementedError,\n INTERNAL: InternalError,\n UNAVAILABLE: UnavailableError,\n DATA_LOSS: DataLossError,\n}\n\n_EXCEPTION_CLASS_TO_CODE = dict((\n (class_, code) for (code, class_) in _CODE_TO_EXCEPTION_CLASS.items()))\n\n\ndef exception_type_from_error_code(error_code):\n return _CODE_TO_EXCEPTION_CLASS[error_code]\n\n\ndef error_code_from_exception_type(cls):\n return _EXCEPTION_CLASS_TO_CODE[cls]\n\n\ndef _make_specific_exception(node_def, op, message, error_code):\n try:\n exc_type = exception_type_from_error_code(error_code)\n return exc_type(node_def, op, message)\n except KeyError:\n warnings.warn(\"Unknown error code: %d\" % error_code)\n return UnknownError(node_def, op, message, error_code)\n\n\[email protected]\ndef raise_exception_on_not_ok_status():\n try:\n status = pywrap_tensorflow.TF_NewStatus()\n yield status\n if pywrap_tensorflow.TF_GetCode(status) != 0:\n raise _make_specific_exception(\n None, None,\n compat.as_text(pywrap_tensorflow.TF_Message(status)),\n pywrap_tensorflow.TF_GetCode(status))\n finally:\n pywrap_tensorflow.TF_DeleteStatus(status)\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for barrier ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import data_flow_ops\n\n\nclass BarrierTest(tf.test.TestCase):\n\n def testConstructorWithShapes(self):\n with tf.Graph().as_default():\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((1, 2, 3), (8,)),\n shared_name=\"B\",\n name=\"B\")\n self.assertTrue(isinstance(b.barrier_ref, tf.Tensor))\n self.assertProtoEquals(\"\"\"\n name:'B' op:'Barrier'\n attr {\n key: \"capacity\"\n value {\n i: -1\n }\n }\n attr { key: 'component_types'\n value { list { type: DT_FLOAT type: DT_FLOAT } } }\n attr {\n key: 'shapes'\n value {\n list {\n shape {\n dim { size: 1 } dim { size: 2 } dim { size: 3 }\n }\n shape {\n dim { size: 8 }\n }\n }\n }\n }\n attr { key: 'container' value { s: \"\" } }\n attr { key: 'shared_name' value: { s: 'B' } }\n \"\"\", b.barrier_ref.op.node_def)\n\n def testInsertMany(self):\n with self.test_session():\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((), ()),\n name=\"B\")\n size_t = b.ready_size()\n self.assertEqual([], size_t.get_shape())\n keys = [b\"a\", b\"b\", b\"c\"]\n insert_0_op = b.insert_many(0, keys, [10.0, 20.0, 30.0])\n insert_1_op = b.insert_many(1, keys, [100.0, 200.0, 300.0])\n\n self.assertEquals(size_t.eval(), [0])\n insert_0_op.run()\n self.assertEquals(size_t.eval(), [0])\n insert_1_op.run()\n self.assertEquals(size_t.eval(), [3])\n\n def testInsertManyEmptyTensor(self):\n with self.test_session():\n error_message = (\"Empty tensors are not supported, but received shape \"\n r\"\\'\\(0,\\)\\' at index 1\")\n with self.assertRaisesRegexp(ValueError, error_message):\n data_flow_ops.Barrier((tf.float32, tf.float32),\n shapes=((1,), (0,)),\n name=\"B\")\n\n def testInsertManyEmptyTensorUnknown(self):\n with self.test_session():\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n name=\"B\")\n size_t = b.ready_size()\n self.assertEqual([], size_t.get_shape())\n keys = [b\"a\", b\"b\", b\"c\"]\n insert_0_op = b.insert_many(0, keys, np.array([[], [], []], np.float32))\n self.assertEquals(size_t.eval(), [0])\n with self.assertRaisesOpError(\n \".*Tensors with no elements are not supported.*\"):\n insert_0_op.run()\n\n def testTakeMany(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((), ()),\n name=\"B\")\n size_t = b.ready_size()\n keys = [b\"a\", b\"b\", b\"c\"]\n values_0 = [10.0, 20.0, 30.0]\n values_1 = [100.0, 200.0, 300.0]\n insert_0_op = b.insert_many(0, keys, values_0)\n insert_1_op = b.insert_many(1, keys, values_1)\n take_t = b.take_many(3)\n\n insert_0_op.run()\n insert_1_op.run()\n self.assertEquals(size_t.eval(), [3])\n\n indices_val, keys_val, values_0_val, values_1_val = sess.run([\n take_t[0], take_t[1], take_t[2][0], take_t[2][1]])\n\n self.assertAllEqual(indices_val, [-2**63] * 3)\n for k, v0, v1 in zip(keys, values_0, values_1):\n idx = keys_val.tolist().index(k)\n self.assertEqual(values_0_val[idx], v0)\n self.assertEqual(values_1_val[idx], v1)\n\n def testTakeManySmallBatch(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((), ()),\n name=\"B\")\n size_t = b.ready_size()\n size_i = b.incomplete_size()\n keys = [b\"a\", b\"b\", b\"c\", b\"d\"]\n values_0 = [10.0, 20.0, 30.0, 40.0]\n values_1 = [100.0, 200.0, 300.0, 400.0]\n insert_0_op = b.insert_many(0, keys, values_0)\n # Split adding of the second component into two independent operations.\n # After insert_1_1_op, we'll have two ready elements in the barrier,\n # 2 will still be incomplete.\n insert_1_1_op = b.insert_many(1, keys[0:2], values_1[0:2]) # add \"a\", \"b\"\n insert_1_2_op = b.insert_many(1, keys[2:3], values_1[2:3]) # add \"c\"\n insert_1_3_op = b.insert_many(1, keys[3:], values_1[3:]) # add \"d\"\n insert_empty_op = b.insert_many(0, [], [])\n close_op = b.close()\n close_op_final = b.close(cancel_pending_enqueues=True)\n index_t, key_t, value_list_t = b.take_many(3, allow_small_batch=True)\n insert_0_op.run()\n insert_1_1_op.run()\n close_op.run()\n # Now we have a closed barrier with 2 ready elements. Running take_t\n # should return a reduced batch with 2 elements only.\n self.assertEquals(size_i.eval(), [2]) # assert that incomplete size = 2\n self.assertEquals(size_t.eval(), [2]) # assert that ready size = 2\n _, keys_val, values_0_val, values_1_val = sess.run([\n index_t, key_t, value_list_t[0], value_list_t[1]\n ])\n # Check that correct values have been returned.\n for k, v0, v1 in zip(keys[0:2], values_0[0:2], values_1[0:2]):\n idx = keys_val.tolist().index(k)\n self.assertEqual(values_0_val[idx], v0)\n self.assertEqual(values_1_val[idx], v1)\n\n # The next insert completes the element with key \"c\". The next take_t\n # should return a batch with just 1 element.\n insert_1_2_op.run()\n self.assertEquals(size_i.eval(), [1]) # assert that incomplete size = 1\n self.assertEquals(size_t.eval(), [1]) # assert that ready size = 1\n _, keys_val, values_0_val, values_1_val = sess.run([\n index_t, key_t, value_list_t[0], value_list_t[1]\n ])\n # Check that correct values have been returned.\n for k, v0, v1 in zip(keys[2:3], values_0[2:3], values_1[2:3]):\n idx = keys_val.tolist().index(k)\n self.assertEqual(values_0_val[idx], v0)\n self.assertEqual(values_1_val[idx], v1)\n\n # Adding nothing ought to work, even if the barrier is closed.\n insert_empty_op.run()\n\n # currently keys \"a\" and \"b\" are not in the barrier, adding them\n # again after it has been closed, ought to cause failure.\n with self.assertRaisesOpError(\"is closed\"):\n insert_1_1_op.run()\n close_op_final.run()\n\n # These ops should fail because the barrier has now been closed with\n # cancel_pending_enqueues = True.\n with self.assertRaisesOpError(\"is closed\"):\n insert_empty_op.run()\n with self.assertRaisesOpError(\"is closed\"):\n insert_1_3_op.run()\n\n def testUseBarrierWithShape(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((2, 2), (8,)),\n name=\"B\")\n size_t = b.ready_size()\n keys = [b\"a\", b\"b\", b\"c\"]\n values_0 = np.array(\n [[[10.0] * 2] * 2, [[20.0] * 2] * 2, [[30.0] * 2] * 2], np.float32)\n values_1 = np.array([[100.0] * 8, [200.0] * 8, [300.0] * 8],\n np.float32)\n insert_0_op = b.insert_many(0, keys, values_0)\n insert_1_op = b.insert_many(1, keys, values_1)\n take_t = b.take_many(3)\n\n insert_0_op.run()\n insert_1_op.run()\n self.assertEquals(size_t.eval(), [3])\n\n indices_val, keys_val, values_0_val, values_1_val = sess.run([\n take_t[0], take_t[1], take_t[2][0], take_t[2][1]])\n self.assertAllEqual(indices_val, [-2**63] * 3)\n self.assertShapeEqual(keys_val, take_t[1])\n self.assertShapeEqual(values_0_val, take_t[2][0])\n self.assertShapeEqual(values_1_val, take_t[2][1])\n\n for k, v0, v1 in zip(keys, values_0, values_1):\n idx = keys_val.tolist().index(k)\n self.assertAllEqual(values_0_val[idx], v0)\n self.assertAllEqual(values_1_val[idx], v1)\n\n def testParallelInsertMany(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(tf.float32, shapes=())\n size_t = b.ready_size()\n keys = [str(x).encode(\"ascii\") for x in range(10)]\n values = [float(x) for x in range(10)]\n insert_ops = [b.insert_many(0, [k], [v]) for k, v in zip(keys, values)]\n take_t = b.take_many(10)\n\n sess.run(insert_ops)\n self.assertEquals(size_t.eval(), [10])\n\n indices_val, keys_val, values_val = sess.run(\n [take_t[0], take_t[1], take_t[2][0]])\n\n self.assertAllEqual(indices_val, [-2**63 + x for x in range(10)])\n for k, v in zip(keys, values):\n idx = keys_val.tolist().index(k)\n self.assertEqual(values_val[idx], v)\n\n def testParallelTakeMany(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(tf.float32, shapes=())\n size_t = b.ready_size()\n keys = [str(x).encode(\"ascii\") for x in range(10)]\n values = [float(x) for x in range(10)]\n insert_op = b.insert_many(0, keys, values)\n take_t = [b.take_many(1) for _ in keys]\n\n insert_op.run()\n self.assertEquals(size_t.eval(), [10])\n\n index_fetches = []\n key_fetches = []\n value_fetches = []\n for ix_t, k_t, v_t in take_t:\n index_fetches.append(ix_t)\n key_fetches.append(k_t)\n value_fetches.append(v_t[0])\n vals = sess.run(index_fetches + key_fetches + value_fetches)\n\n index_vals = vals[:len(keys)]\n key_vals = vals[len(keys):2 * len(keys)]\n value_vals = vals[2 * len(keys):]\n\n taken_elems = []\n for k, v in zip(key_vals, value_vals):\n taken_elems.append((k[0], v[0]))\n\n self.assertAllEqual(np.hstack(index_vals), [-2**63] * 10)\n\n self.assertItemsEqual(\n zip(keys, values),\n [(k[0], v[0]) for k, v in zip(key_vals, value_vals)])\n\n def testBlockingTakeMany(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(tf.float32, shapes=())\n keys = [str(x).encode(\"ascii\") for x in range(10)]\n values = [float(x) for x in range(10)]\n insert_ops = [b.insert_many(0, [k], [v]) for k, v in zip(keys, values)]\n take_t = b.take_many(10)\n\n def take():\n indices_val, keys_val, values_val = sess.run(\n [take_t[0], take_t[1], take_t[2][0]])\n self.assertAllEqual(\n indices_val, [int(x.decode(\"ascii\")) - 2**63 for x in keys_val])\n self.assertItemsEqual(zip(keys, values), zip(keys_val, values_val))\n\n t = self.checkedThread(target=take)\n t.start()\n time.sleep(0.1)\n for insert_op in insert_ops:\n insert_op.run()\n t.join()\n\n def testParallelInsertManyTakeMany(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.int64), shapes=((), (2,)))\n num_iterations = 100\n keys = [str(x) for x in range(10)]\n values_0 = np.asarray(range(10), dtype=np.float32)\n values_1 = np.asarray([[x+1, x + 2] for x in range(10)], dtype=np.int64)\n keys_i = lambda i: [(\"%d:%s\" % (i, k)).encode(\"ascii\") for k in keys]\n insert_0_ops = [\n b.insert_many(0, keys_i(i), values_0 + i)\n for i in range(num_iterations)]\n insert_1_ops = [\n b.insert_many(1, keys_i(i), values_1 + i)\n for i in range(num_iterations)]\n take_ops = [b.take_many(10) for _ in range(num_iterations)]\n\n def take(sess, i, taken):\n indices_val, keys_val, values_0_val, values_1_val = sess.run(\n [take_ops[i][0], take_ops[i][1],\n take_ops[i][2][0], take_ops[i][2][1]])\n taken.append({\"indices\": indices_val,\n \"keys\": keys_val,\n \"values_0\": values_0_val,\n \"values_1\": values_1_val})\n\n def insert(sess, i):\n sess.run([insert_0_ops[i], insert_1_ops[i]])\n\n taken = []\n\n take_threads = [\n self.checkedThread(target=take, args=(sess, i, taken))\n for i in range(num_iterations)]\n insert_threads = [\n self.checkedThread(target=insert, args=(sess, i))\n for i in range(num_iterations)]\n\n for t in take_threads:\n t.start()\n time.sleep(0.1)\n for t in insert_threads:\n t.start()\n for t in take_threads:\n t.join()\n for t in insert_threads:\n t.join()\n\n self.assertEquals(len(taken), num_iterations)\n flatten = lambda l: [item for sublist in l for item in sublist]\n all_indices = sorted(flatten([t_i[\"indices\"] for t_i in taken]))\n all_keys = sorted(flatten([t_i[\"keys\"] for t_i in taken]))\n\n expected_keys = sorted(flatten(\n [keys_i(i) for i in range(num_iterations)]))\n expected_indices = sorted(flatten(\n [-2**63 + j] * 10 for j in range(num_iterations)))\n\n self.assertAllEqual(all_indices, expected_indices)\n self.assertAllEqual(all_keys, expected_keys)\n\n for taken_i in taken:\n outer_indices_from_keys = np.array(\n [int(k.decode(\"ascii\").split(\":\")[0]) for k in taken_i[\"keys\"]])\n inner_indices_from_keys = np.array(\n [int(k.decode(\"ascii\").split(\":\")[1]) for k in taken_i[\"keys\"]])\n self.assertAllEqual(taken_i[\"values_0\"],\n outer_indices_from_keys + inner_indices_from_keys)\n expected_values_1 = np.vstack(\n (1 + outer_indices_from_keys + inner_indices_from_keys,\n 2 + outer_indices_from_keys + inner_indices_from_keys)).T\n self.assertAllEqual(taken_i[\"values_1\"], expected_values_1)\n\n def testClose(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((), ()),\n name=\"B\")\n size_t = b.ready_size()\n incomplete_t = b.incomplete_size()\n keys = [b\"a\", b\"b\", b\"c\"]\n values_0 = [10.0, 20.0, 30.0]\n values_1 = [100.0, 200.0, 300.0]\n insert_0_op = b.insert_many(0, keys, values_0)\n insert_1_op = b.insert_many(1, keys, values_1)\n close_op = b.close()\n fail_insert_op = b.insert_many(0, [\"f\"], [60.0])\n take_t = b.take_many(3)\n take_too_many_t = b.take_many(4)\n\n self.assertEquals(size_t.eval(), [0])\n self.assertEquals(incomplete_t.eval(), [0])\n insert_0_op.run()\n self.assertEquals(size_t.eval(), [0])\n self.assertEquals(incomplete_t.eval(), [3])\n close_op.run()\n\n # This op should fail because the barrier is closed.\n with self.assertRaisesOpError(\"is closed\"):\n fail_insert_op.run()\n\n # This op should succeed because the barrier has not cancelled\n # pending enqueues\n insert_1_op.run()\n self.assertEquals(size_t.eval(), [3])\n self.assertEquals(incomplete_t.eval(), [0])\n\n # This op should fail because the barrier is closed.\n with self.assertRaisesOpError(\"is closed\"):\n fail_insert_op.run()\n\n # This op should fail because we requested more elements than are\n # available in incomplete + ready queue.\n with self.assertRaisesOpError(\n r\"is closed and has insufficient elements \"\n r\"\\(requested 4, total size 3\\)\"):\n sess.run(take_too_many_t[0]) # Sufficient to request just the indices\n\n # This op should succeed because there are still completed elements\n # to process.\n indices_val, keys_val, values_0_val, values_1_val = sess.run(\n [take_t[0], take_t[1], take_t[2][0], take_t[2][1]])\n self.assertAllEqual(indices_val, [-2**63] * 3)\n for k, v0, v1 in zip(keys, values_0, values_1):\n idx = keys_val.tolist().index(k)\n self.assertEqual(values_0_val[idx], v0)\n self.assertEqual(values_1_val[idx], v1)\n\n # This op should fail because there are no more completed elements and\n # the queue is closed.\n with self.assertRaisesOpError(\"is closed and has insufficient elements\"):\n sess.run(take_t[0])\n\n def testCancel(self):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((), ()),\n name=\"B\")\n size_t = b.ready_size()\n incomplete_t = b.incomplete_size()\n keys = [b\"a\", b\"b\", b\"c\"]\n values_0 = [10.0, 20.0, 30.0]\n values_1 = [100.0, 200.0, 300.0]\n insert_0_op = b.insert_many(0, keys, values_0)\n insert_1_op = b.insert_many(1, keys[0:2], values_1[0:2])\n insert_2_op = b.insert_many(1, keys[2:], values_1[2:])\n cancel_op = b.close(cancel_pending_enqueues=True)\n fail_insert_op = b.insert_many(0, [\"f\"], [60.0])\n take_t = b.take_many(2)\n take_too_many_t = b.take_many(3)\n\n self.assertEquals(size_t.eval(), [0])\n insert_0_op.run()\n insert_1_op.run()\n self.assertEquals(size_t.eval(), [2])\n self.assertEquals(incomplete_t.eval(), [1])\n cancel_op.run()\n\n # This op should fail because the queue is closed.\n with self.assertRaisesOpError(\"is closed\"):\n fail_insert_op.run()\n\n # This op should fail because the queue is cancelled.\n with self.assertRaisesOpError(\"is closed\"):\n insert_2_op.run()\n\n # This op should fail because we requested more elements than are\n # available in incomplete + ready queue.\n with self.assertRaisesOpError(\n r\"is closed and has insufficient elements \"\n r\"\\(requested 3, total size 2\\)\"):\n sess.run(take_too_many_t[0]) # Sufficient to request just the indices\n\n # This op should succeed because there are still completed elements\n # to process.\n indices_val, keys_val, values_0_val, values_1_val = sess.run(\n [take_t[0], take_t[1], take_t[2][0], take_t[2][1]])\n self.assertAllEqual(indices_val, [-2**63] * 2)\n for k, v0, v1 in zip(keys[0:2], values_0[0:2], values_1[0:2]):\n idx = keys_val.tolist().index(k)\n self.assertEqual(values_0_val[idx], v0)\n self.assertEqual(values_1_val[idx], v1)\n\n # This op should fail because there are no more completed elements and\n # the queue is closed.\n with self.assertRaisesOpError(\"is closed and has insufficient elements\"):\n sess.run(take_t[0])\n\n def _testClosedEmptyBarrierTakeManyAllowSmallBatchRaises(self, cancel):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.float32), shapes=((), ()), name=\"B\")\n take_t = b.take_many(1, allow_small_batch=True)\n sess.run(b.close(cancel))\n with self.assertRaisesOpError(\"is closed and has insufficient elements\"):\n sess.run(take_t)\n\n def testClosedEmptyBarrierTakeManyAllowSmallBatchRaises(self):\n self._testClosedEmptyBarrierTakeManyAllowSmallBatchRaises(cancel=False)\n self._testClosedEmptyBarrierTakeManyAllowSmallBatchRaises(cancel=True)\n\n def _testParallelInsertManyTakeManyCloseHalfwayThrough(self, cancel):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.int64), shapes=((), (2,)))\n num_iterations = 50\n keys = [str(x) for x in range(10)]\n values_0 = np.asarray(range(10), dtype=np.float32)\n values_1 = np.asarray([[x + 1, x + 2] for x in range(10)], dtype=np.int64)\n keys_i = lambda i: [(\"%d:%s\" % (i, k)).encode(\"ascii\") for k in keys]\n insert_0_ops = [\n b.insert_many(0, keys_i(i), values_0 + i)\n for i in range(num_iterations)]\n insert_1_ops = [\n b.insert_many(1, keys_i(i), values_1 + i)\n for i in range(num_iterations)]\n take_ops = [b.take_many(10) for _ in range(num_iterations)]\n close_op = b.close(cancel_pending_enqueues=cancel)\n\n def take(sess, i, taken):\n try:\n indices_val, unused_keys_val, unused_val_0, unused_val_1 = sess.run(\n [take_ops[i][0], take_ops[i][1],\n take_ops[i][2][0], take_ops[i][2][1]])\n taken.append(len(indices_val))\n except tf.errors.OutOfRangeError:\n taken.append(0)\n\n def insert(sess, i):\n try:\n sess.run([insert_0_ops[i], insert_1_ops[i]])\n except tf.errors.CancelledError:\n pass\n\n taken = []\n\n take_threads = [\n self.checkedThread(target=take, args=(sess, i, taken))\n for i in range(num_iterations)]\n insert_threads = [\n self.checkedThread(target=insert, args=(sess, i))\n for i in range(num_iterations)]\n\n first_half_insert_threads = insert_threads[:num_iterations//2]\n second_half_insert_threads = insert_threads[num_iterations//2:]\n\n for t in take_threads:\n t.start()\n for t in first_half_insert_threads:\n t.start()\n for t in first_half_insert_threads:\n t.join()\n\n close_op.run()\n\n for t in second_half_insert_threads:\n t.start()\n for t in take_threads:\n t.join()\n for t in second_half_insert_threads:\n t.join()\n\n self.assertEqual(\n sorted(taken), [0] * (num_iterations//2) + [10] * (num_iterations//2))\n\n def testParallelInsertManyTakeManyCloseHalfwayThrough(self):\n self._testParallelInsertManyTakeManyCloseHalfwayThrough(cancel=False)\n\n def testParallelInsertManyTakeManyCancelHalfwayThrough(self):\n self._testParallelInsertManyTakeManyCloseHalfwayThrough(cancel=True)\n\n def _testParallelPartialInsertManyTakeManyCloseHalfwayThrough(self, cancel):\n with self.test_session() as sess:\n b = data_flow_ops.Barrier(\n (tf.float32, tf.int64), shapes=((), (2,)))\n num_iterations = 100\n keys = [str(x) for x in range(10)]\n values_0 = np.asarray(range(10), dtype=np.float32)\n values_1 = np.asarray([[x + 1, x + 2] for x in range(10)], dtype=np.int64)\n keys_i = lambda i: [(\"%d:%s\" % (i, k)).encode(\"ascii\") for k in keys]\n insert_0_ops = [\n b.insert_many(0, keys_i(i), values_0 + i, name=\"insert_0_%d\" % i)\n for i in range(num_iterations)]\n\n close_op = b.close(cancel_pending_enqueues=cancel)\n\n take_ops = [b.take_many(10, name=\"take_%d\" % i)\n for i in range(num_iterations)]\n # insert_1_ops will only run after closure\n insert_1_ops = [\n b.insert_many(1, keys_i(i), values_1 + i, name=\"insert_1_%d\" % i)\n for i in range(num_iterations)]\n\n def take(sess, i, taken):\n if cancel:\n try:\n indices_val, unused_keys_val, unused_val_0, unused_val_1 = sess.run(\n [take_ops[i][0], take_ops[i][1],\n take_ops[i][2][0], take_ops[i][2][1]])\n taken.append(len(indices_val))\n except tf.errors.OutOfRangeError:\n taken.append(0)\n else:\n indices_val, unused_keys_val, unused_val_0, unused_val_1 = sess.run(\n [take_ops[i][0], take_ops[i][1],\n take_ops[i][2][0], take_ops[i][2][1]])\n taken.append(len(indices_val))\n\n def insert_0(sess, i):\n insert_0_ops[i].run(session=sess)\n\n def insert_1(sess, i):\n if cancel:\n try:\n insert_1_ops[i].run(session=sess)\n except tf.errors.CancelledError:\n pass\n else:\n insert_1_ops[i].run(session=sess)\n\n taken = []\n\n take_threads = [\n self.checkedThread(target=take, args=(sess, i, taken))\n for i in range(num_iterations)]\n insert_0_threads = [\n self.checkedThread(target=insert_0, args=(sess, i))\n for i in range(num_iterations)]\n insert_1_threads = [\n self.checkedThread(target=insert_1, args=(sess, i))\n for i in range(num_iterations)]\n\n for t in insert_0_threads:\n t.start()\n for t in insert_0_threads:\n t.join()\n for t in take_threads:\n t.start()\n\n close_op.run()\n\n for t in insert_1_threads:\n t.start()\n for t in take_threads:\n t.join()\n for t in insert_1_threads:\n t.join()\n\n if cancel:\n self.assertEqual(taken, [0] * num_iterations)\n else:\n self.assertEqual(taken, [10] * num_iterations)\n\n def testParallelPartialInsertManyTakeManyCloseHalfwayThrough(self):\n self._testParallelPartialInsertManyTakeManyCloseHalfwayThrough(cancel=False)\n\n def testParallelPartialInsertManyTakeManyCancelHalfwayThrough(self):\n self._testParallelPartialInsertManyTakeManyCloseHalfwayThrough(cancel=True)\n\n def testIncompatibleSharedBarrierErrors(self):\n with self.test_session():\n # Do component types and shapes.\n b_a_1 = data_flow_ops.Barrier((tf.float32,), shapes=(()),\n shared_name=\"b_a\")\n b_a_2 = data_flow_ops.Barrier((tf.int32,), shapes=(()),\n shared_name=\"b_a\")\n b_a_1.barrier_ref.eval()\n with self.assertRaisesOpError(\"component types\"):\n b_a_2.barrier_ref.eval()\n\n b_b_1 = data_flow_ops.Barrier((tf.float32,), shapes=(()),\n shared_name=\"b_b\")\n b_b_2 = data_flow_ops.Barrier(\n (tf.float32, tf.int32),\n shapes=((), ()),\n shared_name=\"b_b\")\n b_b_1.barrier_ref.eval()\n with self.assertRaisesOpError(\"component types\"):\n b_b_2.barrier_ref.eval()\n\n b_c_1 = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((2, 2), (8,)),\n shared_name=\"b_c\")\n b_c_2 = data_flow_ops.Barrier(\n (tf.float32, tf.float32), shared_name=\"b_c\")\n b_c_1.barrier_ref.eval()\n with self.assertRaisesOpError(\"component shapes\"):\n b_c_2.barrier_ref.eval()\n\n b_d_1 = data_flow_ops.Barrier(\n (tf.float32, tf.float32), shapes=((), ()),\n shared_name=\"b_d\")\n b_d_2 = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((2, 2), (8,)),\n shared_name=\"b_d\")\n b_d_1.barrier_ref.eval()\n with self.assertRaisesOpError(\"component shapes\"):\n b_d_2.barrier_ref.eval()\n\n b_e_1 = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((2, 2), (8,)),\n shared_name=\"b_e\")\n b_e_2 = data_flow_ops.Barrier(\n (tf.float32, tf.float32),\n shapes=((2, 5), (8,)),\n shared_name=\"b_e\")\n b_e_1.barrier_ref.eval()\n with self.assertRaisesOpError(\"component shapes\"):\n b_e_2.barrier_ref.eval()\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# 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# ==============================================================================\n\"\"\"Maintain moving averages of parameters.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.training import slot_creator\n\n\n# TODO(touts): switch to variables.Variable.\ndef assign_moving_average(variable, value, decay, zero_debias=True, name=None):\n \"\"\"Compute the moving average of a variable.\n\n The moving average of 'variable' updated with 'value' is:\n variable * decay + value * (1 - decay)\n\n The returned Operation sets 'variable' to the newly computed moving average.\n\n The new value of 'variable' can be set with the 'AssignSub' op as:\n variable -= (1 - decay) * (variable - value)\n\n Since variables that are initialized to a `0` value will be `0` biased,\n `zero_debias` optionally enables scaling by the mathematically correct\n debiasing factor of\n 1 - decay ** num_updates\n See `ADAM: A Method for Stochastic Optimization` Section 3 for more details\n (https://arxiv.org/abs/1412.6980).\n\n Args:\n variable: A Variable.\n value: A tensor with the same shape as 'variable'.\n decay: A float Tensor or float value. The moving average decay.\n zero_debias: A python bool. If true, assume the variable is 0-intialized and\n unbias it, as in https://arxiv.org/abs/1412.6980. See docstring in\n `_zero_debias` for more details.\n name: Optional name of the returned operation.\n\n Returns:\n An Operation that updates 'variable' with the newly computed\n moving average.\n \"\"\"\n with ops.name_scope(name, \"AssignMovingAvg\",\n [variable, value, decay]) as scope:\n with ops.colocate_with(variable):\n decay = ops.convert_to_tensor(1.0 - decay, name=\"decay\")\n if decay.dtype != variable.dtype.base_dtype:\n decay = math_ops.cast(decay, variable.dtype.base_dtype)\n if zero_debias:\n update_delta = _zero_debias(variable, value, decay)\n else:\n update_delta = (variable - value) * decay\n return state_ops.assign_sub(variable, update_delta, name=scope)\n\n\ndef weighted_moving_average(value,\n decay,\n weight,\n truediv=True,\n collections=None,\n name=None):\n \"\"\"Compute the weighted moving average of `value`.\n\n Conceptually, the weighted moving average is:\n `moving_average(value * weight) / moving_average(weight)`,\n where a moving average updates by the rule\n `new_value = decay * old_value + (1 - decay) * update`\n Internally, this Op keeps moving average variables of both `value * weight`\n and `weight`.\n\n Args:\n value: A numeric `Tensor`.\n decay: A float `Tensor` or float value. The moving average decay.\n weight: `Tensor` that keeps the current value of a weight.\n Shape should be able to multiply `value`.\n truediv: Boolean, if `True`, dividing by `moving_average(weight)` is\n floating point division. If `False`, use division implied by dtypes.\n collections: List of graph collections keys to add the internal variables\n `value * weight` and `weight` to.\n Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.\n name: Optional name of the returned operation.\n Defaults to \"WeightedMovingAvg\".\n\n Returns:\n An Operation that updates and returns the weighted moving average.\n \"\"\"\n # Unlike assign_moving_average, the weighted moving average doesn't modify\n # user-visible variables. It is the ratio of two internal variables, which are\n # moving averages of the updates. Thus, the signature of this function is\n # quite different than assign_moving_average.\n if collections is None:\n collections = [ops.GraphKeys.GLOBAL_VARIABLES]\n with variable_scope.variable_scope(name, \"WeightedMovingAvg\",\n [value, weight, decay]) as scope:\n value_x_weight_var = variable_scope.get_variable(\n \"value_x_weight\",\n initializer=init_ops.zeros_initializer(value.get_shape(),\n dtype=value.dtype),\n trainable=False,\n collections=collections)\n weight_var = variable_scope.get_variable(\n \"weight\",\n initializer=init_ops.zeros_initializer(weight.get_shape(),\n dtype=weight.dtype),\n trainable=False,\n collections=collections)\n numerator = assign_moving_average(\n value_x_weight_var, value * weight, decay, zero_debias=False)\n denominator = assign_moving_average(\n weight_var, weight, decay, zero_debias=False)\n\n if truediv:\n return math_ops.truediv(numerator, denominator, name=scope.name)\n else:\n return math_ops.div(numerator, denominator, name=scope.name)\n\n\ndef _zero_debias(unbiased_var, value, decay):\n \"\"\"Compute the delta required for a debiased Variable.\n\n All exponential moving averages initialized with Tensors are initialized to 0,\n and therefore are biased to 0. Variables initialized to 0 and used as EMAs are\n similarly biased. This function creates the debias updated amount according to\n a scale factor, as in https://arxiv.org/abs/1412.6980.\n\n To demonstrate the bias the results from 0-initialization, take an EMA that\n was initialized to `0` with decay `b`. After `t` timesteps of seeing the\n constant `c`, the variable have the following value:\n\n ```\n EMA = 0*b^(t) + c*(1 - b)*b^(t-1) + c*(1 - b)*b^(t-2) + ...\n = c*(1 - b^t)\n ```\n\n To have the true value `c`, we would divide by the scale factor `1 - b^t`.\n\n In order to perform debiasing, we use two shadow variables. One keeps track of\n the biased estimate, and the other keeps track of the number of updates that\n have occurred.\n\n Args:\n unbiased_var: A Variable representing the current value of the unbiased EMA.\n value: A Tensor representing the most recent value.\n decay: A Tensor representing `1-decay` for the EMA.\n\n Returns:\n The amount that the unbiased variable should be updated. Computing this\n tensor will also update the shadow variables appropriately.\n \"\"\"\n with variable_scope.variable_scope(\n unbiased_var.op.name, values=[unbiased_var, value, decay]) as scope:\n with ops.colocate_with(unbiased_var):\n with ops.control_dependencies(None):\n biased_initializer = init_ops.zeros_initializer(\n unbiased_var.get_shape(), dtype=unbiased_var.dtype)\n local_step_initializer = init_ops.ones_initializer()\n biased_var = variable_scope.get_variable(\n \"biased\", initializer=biased_initializer, trainable=False)\n # Initializing the local_step to `0` would cause problems with the\n # debiasing equation, so we instead initialize to `1`.\n local_step = variable_scope.get_variable(\n \"local_step\",\n shape=[],\n dtype=unbiased_var.dtype,\n initializer=local_step_initializer,\n trainable=False)\n\n # Get an update ops for both shadow variables.\n update_biased = state_ops.assign_sub(biased_var,\n (biased_var - value) * decay,\n name=scope.name)\n update_local_step = local_step.assign_add(1)\n\n # Compute the value of the delta to update the unbiased EMA. Make sure to\n # use the new values of the biased variable and the local step.\n with ops.control_dependencies([update_biased, update_local_step]):\n # This function gets `1 - decay`, so use `1.0 - decay` in the exponent.\n unbiased_ema_delta = (unbiased_var - biased_var.read_value() /\n (1 - math_ops.pow(\n 1.0 - decay, local_step.read_value())))\n\n return unbiased_ema_delta\n\n\nclass ExponentialMovingAverage(object):\n \"\"\"Maintains moving averages of variables by employing an exponential decay.\n\n When training a model, it is often beneficial to maintain moving averages of\n the trained parameters. Evaluations that use averaged parameters sometimes\n produce significantly better results than the final trained values.\n\n The `apply()` method adds shadow copies of trained variables and add ops that\n maintain a moving average of the trained variables in their shadow copies.\n It is used when building the training model. The ops that maintain moving\n averages are typically run after each training step.\n The `average()` and `average_name()` methods give access to the shadow\n variables and their names. They are useful when building an evaluation\n model, or when restoring a model from a checkpoint file. They help use the\n moving averages in place of the last trained values for evaluations.\n\n The moving averages are computed using exponential decay. You specify the\n decay value when creating the `ExponentialMovingAverage` object. The shadow\n variables are initialized with the same initial values as the trained\n variables. When you run the ops to maintain the moving averages, each\n shadow variable is updated with the formula:\n\n `shadow_variable -= (1 - decay) * (shadow_variable - variable)`\n\n This is mathematically equivalent to the classic formula below, but the use\n of an `assign_sub` op (the `\"-=\"` in the formula) allows concurrent lockless\n updates to the variables:\n\n `shadow_variable = decay * shadow_variable + (1 - decay) * variable`\n\n Reasonable values for `decay` are close to 1.0, typically in the\n multiple-nines range: 0.999, 0.9999, etc.\n\n Example usage when creating a training model:\n\n ```python\n # Create variables.\n var0 = tf.Variable(...)\n var1 = tf.Variable(...)\n # ... use the variables to build a training model...\n ...\n # Create an op that applies the optimizer. This is what we usually\n # would use as a training op.\n opt_op = opt.minimize(my_loss, [var0, var1])\n\n # Create an ExponentialMovingAverage object\n ema = tf.train.ExponentialMovingAverage(decay=0.9999)\n\n # Create the shadow variables, and add ops to maintain moving averages\n # of var0 and var1.\n maintain_averages_op = ema.apply([var0, var1])\n\n # Create an op that will update the moving averages after each training\n # step. This is what we will use in place of the usual training op.\n with tf.control_dependencies([opt_op]):\n training_op = tf.group(maintain_averages_op)\n\n ...train the model by running training_op...\n ```\n\n There are two ways to use the moving averages for evaluations:\n\n * Build a model that uses the shadow variables instead of the variables.\n For this, use the `average()` method which returns the shadow variable\n for a given variable.\n * Build a model normally but load the checkpoint files to evaluate by using\n the shadow variable names. For this use the `average_name()` method. See\n the [Saver class](../../api_docs/python/train.md#Saver) for more\n information on restoring saved variables.\n\n Example of restoring the shadow variable values:\n\n ```python\n # Create a Saver that loads variables from their saved shadow values.\n shadow_var0_name = ema.average_name(var0)\n shadow_var1_name = ema.average_name(var1)\n saver = tf.train.Saver({shadow_var0_name: var0, shadow_var1_name: var1})\n saver.restore(...checkpoint filename...)\n # var0 and var1 now hold the moving average values\n ```\n\n @@__init__\n @@apply\n @@average_name\n @@average\n @@variables_to_restore\n \"\"\"\n\n def __init__(self, decay, num_updates=None, zero_debias=False,\n name=\"ExponentialMovingAverage\"):\n \"\"\"Creates a new ExponentialMovingAverage object.\n\n The `apply()` method has to be called to create shadow variables and add\n ops to maintain moving averages.\n\n The optional `num_updates` parameter allows one to tweak the decay rate\n dynamically. It is typical to pass the count of training steps, usually\n kept in a variable that is incremented at each step, in which case the\n decay rate is lower at the start of training. This makes moving averages\n move faster. If passed, the actual decay rate used is:\n\n `min(decay, (1 + num_updates) / (10 + num_updates))`\n\n Args:\n decay: Float. The decay to use.\n num_updates: Optional count of number of updates applied to variables.\n zero_debias: If `True`, zero debias moving-averages that are initialized\n with tensors.\n name: String. Optional prefix name to use for the name of ops added in\n `apply()`.\n \"\"\"\n self._decay = decay\n self._num_updates = num_updates\n self._zero_debias = zero_debias\n self._name = name\n self._averages = {}\n\n def apply(self, var_list=None):\n \"\"\"Maintains moving averages of variables.\n\n `var_list` must be a list of `Variable` or `Tensor` objects. This method\n creates shadow variables for all elements of `var_list`. Shadow variables\n for `Variable` objects are initialized to the variable's initial value.\n They will be added to the `GraphKeys.MOVING_AVERAGE_VARIABLES` collection.\n For `Tensor` objects, the shadow variables are initialized to 0 and zero\n debiased (see docstring in `assign_moving_average` for more details).\n\n shadow variables are created with `trainable=False` and added to the\n `GraphKeys.ALL_VARIABLES` collection. They will be returned by calls to\n `tf.global_variables()`.\n\n Returns an op that updates all shadow variables as described above.\n\n Note that `apply()` can be called multiple times with different lists of\n variables.\n\n Args:\n var_list: A list of Variable or Tensor objects. The variables\n and Tensors must be of types float16, float32, or float64.\n\n Returns:\n An Operation that updates the moving averages.\n\n Raises:\n TypeError: If the arguments are not all float16, float32, or float64.\n ValueError: If the moving average of one of the variables is already\n being computed.\n \"\"\"\n # TODO(touts): op_scope\n if var_list is None:\n var_list = variables.trainable_variables()\n zero_debias_true = set() # set of vars to set `zero_debias=True`\n for var in var_list:\n if var.dtype.base_dtype not in [dtypes.float16, dtypes.float32,\n dtypes.float64]:\n raise TypeError(\"The variables must be half, float, or double: %s\" %\n var.name)\n if var in self._averages:\n raise ValueError(\"Moving average already computed for: %s\" % var.name)\n\n # For variables: to lower communication bandwidth across devices we keep\n # the moving averages on the same device as the variables. For other\n # tensors, we rely on the existing device allocation mechanism.\n with ops.control_dependencies(None):\n if isinstance(var, variables.Variable):\n avg = slot_creator.create_slot(var,\n var.initialized_value(),\n self._name,\n colocate_with_primary=True)\n # NOTE(mrry): We only add `tf.Variable` objects to the\n # `MOVING_AVERAGE_VARIABLES` collection.\n ops.add_to_collection(ops.GraphKeys.MOVING_AVERAGE_VARIABLES, var)\n else:\n avg = slot_creator.create_zeros_slot(\n var,\n self._name,\n colocate_with_primary=(var.op.type in [\"Variable\", \"VariableV2\"]))\n if self._zero_debias:\n zero_debias_true.add(avg)\n self._averages[var] = avg\n\n with ops.name_scope(self._name) as scope:\n decay = ops.convert_to_tensor(self._decay, name=\"decay\")\n if self._num_updates is not None:\n num_updates = math_ops.cast(self._num_updates,\n dtypes.float32,\n name=\"num_updates\")\n decay = math_ops.minimum(decay,\n (1.0 + num_updates) / (10.0 + num_updates))\n updates = []\n for var in var_list:\n zero_debias = self._averages[var] in zero_debias_true\n updates.append(assign_moving_average(\n self._averages[var], var, decay, zero_debias=zero_debias))\n return control_flow_ops.group(*updates, name=scope)\n\n def average(self, var):\n \"\"\"Returns the `Variable` holding the average of `var`.\n\n Args:\n var: A `Variable` object.\n\n Returns:\n A `Variable` object or `None` if the moving average of `var`\n is not maintained.\n \"\"\"\n return self._averages.get(var, None)\n\n def average_name(self, var):\n \"\"\"Returns the name of the `Variable` holding the average for `var`.\n\n The typical scenario for `ExponentialMovingAverage` is to compute moving\n averages of variables during training, and restore the variables from the\n computed moving averages during evaluations.\n\n To restore variables, you have to know the name of the shadow variables.\n That name and the original variable can then be passed to a `Saver()` object\n to restore the variable from the moving average value with:\n `saver = tf.train.Saver({ema.average_name(var): var})`\n\n `average_name()` can be called whether or not `apply()` has been called.\n\n Args:\n var: A `Variable` object.\n\n Returns:\n A string: The name of the variable that will be used or was used\n by the `ExponentialMovingAverage class` to hold the moving average of\n `var`.\n \"\"\"\n if var in self._averages:\n return self._averages[var].op.name\n return ops.get_default_graph().unique_name(\n var.op.name + \"/\" + self._name, mark_as_used=False)\n\n def variables_to_restore(self, moving_avg_variables=None):\n \"\"\"Returns a map of names to `Variables` to restore.\n\n If a variable has a moving average, use the moving average variable name as\n the restore name; otherwise, use the variable name.\n\n For example,\n\n ```python\n variables_to_restore = ema.variables_to_restore()\n saver = tf.train.Saver(variables_to_restore)\n ```\n\n Below is an example of such mapping:\n\n ```\n conv/batchnorm/gamma/ExponentialMovingAverage: conv/batchnorm/gamma,\n conv_4/conv2d_params/ExponentialMovingAverage: conv_4/conv2d_params,\n global_step: global_step\n ```\n Args:\n moving_avg_variables: a list of variables that require to use of the\n moving variable name to be restored. If None, it will default to\n variables.moving_average_variables() + variables.trainable_variables()\n\n Returns:\n A map from restore_names to variables. The restore_name can be the\n moving_average version of the variable name if it exist, or the original\n variable name.\n \"\"\"\n name_map = {}\n if moving_avg_variables is None:\n # Include trainable variables and variables which have been explicitly\n # added to the moving_average_variables collection.\n moving_avg_variables = variables.trainable_variables()\n moving_avg_variables += variables.moving_average_variables()\n # Remove duplicates\n moving_avg_variables = set(moving_avg_variables)\n # Collect all the variables with moving average,\n for v in moving_avg_variables:\n name_map[self.average_name(v)] = v\n # Make sure we restore variables without moving average as well.\n for v in list(set(variables.global_variables()) - moving_avg_variables):\n if v.op.name not in name_map:\n name_map[v.op.name] = v\n return name_map\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for tensorflow.python.framework.importer.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport random\n\nimport tensorflow as tf\n\nfrom tensorflow.core.util import test_log_pb2\nfrom tensorflow.python.platform import benchmark\n\n\n# Used by SomeRandomBenchmark class below.\n_ran_somebenchmark_1 = [False]\n_ran_somebenchmark_2 = [False]\n_ran_somebenchmark_but_shouldnt = [False]\n\n\nclass SomeRandomBenchmark(tf.test.Benchmark):\n \"\"\"This Benchmark should automatically be registered in the registry.\"\"\"\n\n def _dontRunThisBenchmark(self):\n _ran_somebenchmark_but_shouldnt[0] = True\n\n def notBenchmarkMethod(self):\n _ran_somebenchmark_but_shouldnt[0] = True\n\n def benchmark1(self):\n _ran_somebenchmark_1[0] = True\n\n def benchmark2(self):\n _ran_somebenchmark_2[0] = True\n\n\nclass TestReportingBenchmark(tf.test.Benchmark):\n \"\"\"This benchmark (maybe) reports some stuff.\"\"\"\n\n def benchmarkReport1(self):\n self.report_benchmark(iters=1)\n\n def benchmarkReport2(self):\n self.report_benchmark(\n iters=2, name=\"custom_benchmark_name\",\n extras={\"number_key\": 3, \"other_key\": \"string\"})\n\n def benchmark_times_an_op(self):\n with tf.Session() as sess:\n a = tf.constant(0.0)\n a_plus_a = a + a\n self.run_op_benchmark(\n sess, a_plus_a, min_iters=1000, store_trace=True,\n name=\"op_benchmark\")\n\n\nclass BenchmarkTest(tf.test.TestCase):\n\n def testGlobalBenchmarkRegistry(self):\n registry = list(benchmark.GLOBAL_BENCHMARK_REGISTRY)\n self.assertEqual(len(registry), 2)\n self.assertTrue(SomeRandomBenchmark in registry)\n self.assertTrue(TestReportingBenchmark in registry)\n\n def testRunSomeRandomBenchmark(self):\n # Validate that SomeBenchmark has not run yet\n self.assertFalse(_ran_somebenchmark_1[0])\n self.assertFalse(_ran_somebenchmark_2[0])\n self.assertFalse(_ran_somebenchmark_but_shouldnt[0])\n\n # Run other benchmarks, but this wont run the one we care about\n benchmark._run_benchmarks(\"unrelated\")\n\n # Validate that SomeBenchmark has not run yet\n self.assertFalse(_ran_somebenchmark_1[0])\n self.assertFalse(_ran_somebenchmark_2[0])\n self.assertFalse(_ran_somebenchmark_but_shouldnt[0])\n\n # Run all the benchmarks, avoid generating any reports\n if benchmark.TEST_REPORTER_TEST_ENV in os.environ:\n del os.environ[benchmark.TEST_REPORTER_TEST_ENV]\n benchmark._run_benchmarks(\"SomeRandom\")\n\n # Validate that SomeRandomBenchmark ran correctly\n self.assertTrue(_ran_somebenchmark_1[0])\n self.assertTrue(_ran_somebenchmark_2[0])\n self.assertFalse(_ran_somebenchmark_but_shouldnt[0])\n\n _ran_somebenchmark_1[0] = False\n _ran_somebenchmark_2[0] = False\n _ran_somebenchmark_but_shouldnt[0] = False\n\n # Test running a specific method of SomeRandomBenchmark\n if benchmark.TEST_REPORTER_TEST_ENV in os.environ:\n del os.environ[benchmark.TEST_REPORTER_TEST_ENV]\n benchmark._run_benchmarks(\"SomeRandom.*1$\")\n\n self.assertTrue(_ran_somebenchmark_1[0])\n self.assertFalse(_ran_somebenchmark_2[0])\n self.assertFalse(_ran_somebenchmark_but_shouldnt[0])\n\n def testReportingBenchmark(self):\n tempdir = tf.test.get_temp_dir()\n try:\n tf.gfile.MakeDirs(tempdir)\n except OSError as e:\n # It's OK if the directory already exists.\n if \" exists:\" not in str(e):\n raise e\n\n prefix = os.path.join(\n tempdir, \"reporting_bench_%016x_\" % random.getrandbits(64))\n expected_output_file = \"%s%s\" % (\n prefix, \"TestReportingBenchmark.benchmarkReport1\")\n expected_output_file_2 = \"%s%s\" % (\n prefix, \"TestReportingBenchmark.custom_benchmark_name\")\n expected_output_file_3 = \"%s%s\" % (\n prefix, \"TestReportingBenchmark.op_benchmark\")\n try:\n self.assertFalse(tf.gfile.Exists(expected_output_file))\n # Run benchmark but without env, shouldn't write anything\n if benchmark.TEST_REPORTER_TEST_ENV in os.environ:\n del os.environ[benchmark.TEST_REPORTER_TEST_ENV]\n reporting = TestReportingBenchmark()\n reporting.benchmarkReport1() # This should run without writing anything\n self.assertFalse(tf.gfile.Exists(expected_output_file))\n\n # Runbenchmark with env, should write\n os.environ[benchmark.TEST_REPORTER_TEST_ENV] = prefix\n\n reporting = TestReportingBenchmark()\n reporting.benchmarkReport1() # This should write\n reporting.benchmarkReport2() # This should write\n reporting.benchmark_times_an_op() # This should write\n\n # Check the files were written\n self.assertTrue(tf.gfile.Exists(expected_output_file))\n self.assertTrue(tf.gfile.Exists(expected_output_file_2))\n self.assertTrue(tf.gfile.Exists(expected_output_file_3))\n\n # Check the contents are correct\n expected_1 = test_log_pb2.BenchmarkEntry()\n expected_1.name = \"TestReportingBenchmark.benchmarkReport1\"\n expected_1.iters = 1\n\n expected_2 = test_log_pb2.BenchmarkEntry()\n expected_2.name = \"TestReportingBenchmark.custom_benchmark_name\"\n expected_2.iters = 2\n expected_2.extras[\"number_key\"].double_value = 3\n expected_2.extras[\"other_key\"].string_value = \"string\"\n\n expected_3 = test_log_pb2.BenchmarkEntry()\n expected_3.name = \"TestReportingBenchmark.op_benchmark\"\n expected_3.iters = 1000\n\n def read_benchmark_entry(f):\n s = tf.gfile.GFile(f, \"rb\").read()\n entries = test_log_pb2.BenchmarkEntries.FromString(s)\n self.assertEquals(1, len(entries.entry))\n return entries.entry[0]\n\n read_benchmark_1 = read_benchmark_entry(expected_output_file)\n self.assertProtoEquals(expected_1, read_benchmark_1)\n\n read_benchmark_2 = read_benchmark_entry(expected_output_file_2)\n self.assertProtoEquals(expected_2, read_benchmark_2)\n\n read_benchmark_3 = read_benchmark_entry(expected_output_file_3)\n self.assertEquals(expected_3.name, read_benchmark_3.name)\n self.assertEquals(expected_3.iters, read_benchmark_3.iters)\n self.assertGreater(read_benchmark_3.wall_time, 0)\n full_trace = read_benchmark_3.extras[\"full_trace_chrome_format\"]\n json_trace = json.loads(full_trace.string_value)\n self.assertTrue(isinstance(json_trace, dict))\n self.assertTrue(\"traceEvents\" in json_trace.keys())\n\n finally:\n tf.gfile.DeleteRecursively(tempdir)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2016 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\"\"\"\nThis is an example of using convolutional networks over characters\nfor DBpedia dataset to predict class from description of an entity.\n\nThis model is similar to one described in this paper:\n \"Character-level Convolutional Networks for Text Classification\"\n http://arxiv.org/abs/1509.01626\n\nand is somewhat alternative to the Lua code from here:\n https://github.com/zhangxiangxiao/Crepe\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport sys\n\nimport numpy as np\nimport pandas\nfrom sklearn import metrics\nimport tensorflow as tf\n\nfrom tensorflow.contrib import learn\n\nFLAGS = None\n\nMAX_DOCUMENT_LENGTH = 100\nN_FILTERS = 10\nFILTER_SHAPE1 = [20, 256]\nFILTER_SHAPE2 = [20, N_FILTERS]\nPOOLING_WINDOW = 4\nPOOLING_STRIDE = 2\n\n\ndef char_cnn_model(features, target):\n \"\"\"Character level convolutional neural network model to predict classes.\"\"\"\n target = tf.one_hot(target, 15, 1, 0)\n byte_list = tf.reshape(tf.one_hot(features, 256, 1, 0),\n [-1, MAX_DOCUMENT_LENGTH, 256, 1])\n with tf.variable_scope('CNN_Layer1'):\n # Apply Convolution filtering on input sequence.\n conv1 = tf.contrib.layers.convolution2d(\n byte_list, N_FILTERS, FILTER_SHAPE1, padding='VALID')\n # Add a RELU for non linearity.\n conv1 = tf.nn.relu(conv1)\n # Max pooling across output of Convolution+Relu.\n pool1 = tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1],\n strides=[1, POOLING_STRIDE, 1, 1], padding='SAME')\n # Transpose matrix so that n_filters from convolution becomes width.\n pool1 = tf.transpose(pool1, [0, 1, 3, 2])\n with tf.variable_scope('CNN_Layer2'):\n # Second level of convolution filtering.\n conv2 = tf.contrib.layers.convolution2d(\n pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID')\n # Max across each filter to get useful features for classification.\n pool2 = tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1])\n\n # Apply regular WX + B and classification.\n logits = tf.contrib.layers.fully_connected(pool2, 15, activation_fn=None)\n loss = tf.contrib.losses.softmax_cross_entropy(logits, target)\n\n train_op = tf.contrib.layers.optimize_loss(\n loss, tf.contrib.framework.get_global_step(),\n optimizer='Adam', learning_rate=0.01)\n\n return (\n {'class': tf.argmax(logits, 1), 'prob': tf.nn.softmax(logits)},\n loss, train_op)\n\n\ndef main(unused_argv):\n # Prepare training and testing data\n dbpedia = learn.datasets.load_dataset(\n 'dbpedia', test_with_fake_data=FLAGS.test_with_fake_data, size='large')\n x_train = pandas.DataFrame(dbpedia.train.data)[1]\n y_train = pandas.Series(dbpedia.train.target)\n x_test = pandas.DataFrame(dbpedia.test.data)[1]\n y_test = pandas.Series(dbpedia.test.target)\n\n # Process vocabulary\n char_processor = learn.preprocessing.ByteProcessor(MAX_DOCUMENT_LENGTH)\n x_train = np.array(list(char_processor.fit_transform(x_train)))\n x_test = np.array(list(char_processor.transform(x_test)))\n\n # Build model\n classifier = learn.Estimator(model_fn=char_cnn_model)\n\n # Train and predict\n classifier.fit(x_train, y_train, steps=100)\n y_predicted = [\n p['class'] for p in classifier.predict(x_test, as_iterable=True)]\n score = metrics.accuracy_score(y_test, y_predicted)\n print('Accuracy: {0:f}'.format(score))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--test_with_fake_data',\n default=False,\n help='Test the example code with fake data.',\n action='store_true'\n )\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n", "# Copyright 2016 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\"\"\"Tests for TensorFlow Debugger (tfdbg) Utilities.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.debug import debug_utils\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\n\n\nclass DebugUtilsTest(test_util.TensorFlowTestCase):\n\n @classmethod\n def setUpClass(cls):\n cls._sess = session.Session()\n with cls._sess:\n cls._a_init_val = np.array([[5.0, 3.0], [-1.0, 0.0]])\n cls._b_init_val = np.array([[2.0], [-1.0]])\n cls._c_val = np.array([[-4.0], [np.nan]])\n\n cls._a_init = constant_op.constant(\n cls._a_init_val, shape=[2, 2], name=\"a1_init\")\n cls._b_init = constant_op.constant(\n cls._b_init_val, shape=[2, 1], name=\"b_init\")\n\n cls._a = variables.Variable(cls._a_init, name=\"a1\")\n cls._b = variables.Variable(cls._b_init, name=\"b\")\n cls._c = constant_op.constant(cls._c_val, shape=[2, 1], name=\"c\")\n\n # Matrix product of a and b.\n cls._p = math_ops.matmul(cls._a, cls._b, name=\"p1\")\n\n # Sum of two vectors.\n cls._s = math_ops.add(cls._p, cls._c, name=\"s\")\n\n cls._graph = cls._sess.graph\n\n # These are all the expected nodes in the graph:\n # Two variables (a, b), each with four nodes (Variable, init, Assign,\n # read).\n # One constant (c).\n # One add operation and one matmul operation.\n cls._expected_num_nodes = 4 * 2 + 1 + 1 + 1\n\n def setUp(self):\n self._run_options = config_pb2.RunOptions()\n\n def _verify_watches(self, watch_opts, expected_output_slot,\n expected_debug_ops, expected_debug_urls):\n \"\"\"Verify a list of debug tensor watches.\n\n This requires all watches in the watch list have exactly the same\n output_slot, debug_ops and debug_urls.\n\n Args:\n watch_opts: Repeated protobuf field of DebugTensorWatch.\n expected_output_slot: Expected output slot index, as an integer.\n expected_debug_ops: Expected debug ops, as a list of strings.\n expected_debug_urls: Expected debug URLs, as a list of strings.\n\n Returns:\n List of node names from the list of debug tensor watches.\n \"\"\"\n node_names = []\n for watch in watch_opts:\n node_names.append(watch.node_name)\n\n self.assertEqual(expected_output_slot, watch.output_slot)\n self.assertEqual(expected_debug_ops, watch.debug_ops)\n self.assertEqual(expected_debug_urls, watch.debug_urls)\n\n return node_names\n\n def testAddDebugTensorWatches_defaultDebugOp(self):\n debug_utils.add_debug_tensor_watch(\n self._run_options, \"foo/node_a\", 1, debug_urls=\"file:///tmp/tfdbg_1\")\n debug_utils.add_debug_tensor_watch(\n self._run_options, \"foo/node_b\", 0, debug_urls=\"file:///tmp/tfdbg_2\")\n\n debug_watch_opts = self._run_options.debug_options.debug_tensor_watch_opts\n self.assertEqual(2, len(debug_watch_opts))\n\n watch_0 = debug_watch_opts[0]\n watch_1 = debug_watch_opts[1]\n\n self.assertEqual(\"foo/node_a\", watch_0.node_name)\n self.assertEqual(1, watch_0.output_slot)\n self.assertEqual(\"foo/node_b\", watch_1.node_name)\n self.assertEqual(0, watch_1.output_slot)\n # Verify default debug op name.\n self.assertEqual([\"DebugIdentity\"], watch_0.debug_ops)\n self.assertEqual([\"DebugIdentity\"], watch_1.debug_ops)\n\n # Verify debug URLs.\n self.assertEqual([\"file:///tmp/tfdbg_1\"], watch_0.debug_urls)\n self.assertEqual([\"file:///tmp/tfdbg_2\"], watch_1.debug_urls)\n\n def testAddDebugTensorWatches_explicitDebugOp(self):\n debug_utils.add_debug_tensor_watch(\n self._run_options,\n \"foo/node_a\",\n 0,\n debug_ops=\"DebugNanCount\",\n debug_urls=\"file:///tmp/tfdbg_1\")\n\n debug_watch_opts = self._run_options.debug_options.debug_tensor_watch_opts\n self.assertEqual(1, len(debug_watch_opts))\n\n watch_0 = debug_watch_opts[0]\n\n self.assertEqual(\"foo/node_a\", watch_0.node_name)\n self.assertEqual(0, watch_0.output_slot)\n\n # Verify default debug op name.\n self.assertEqual([\"DebugNanCount\"], watch_0.debug_ops)\n\n # Verify debug URLs.\n self.assertEqual([\"file:///tmp/tfdbg_1\"], watch_0.debug_urls)\n\n def testAddDebugTensorWatches_multipleDebugOps(self):\n debug_utils.add_debug_tensor_watch(\n self._run_options,\n \"foo/node_a\",\n 0,\n debug_ops=[\"DebugNanCount\", \"DebugIdentity\"],\n debug_urls=\"file:///tmp/tfdbg_1\")\n\n debug_watch_opts = self._run_options.debug_options.debug_tensor_watch_opts\n self.assertEqual(1, len(debug_watch_opts))\n\n watch_0 = debug_watch_opts[0]\n\n self.assertEqual(\"foo/node_a\", watch_0.node_name)\n self.assertEqual(0, watch_0.output_slot)\n\n # Verify default debug op name.\n self.assertEqual([\"DebugNanCount\", \"DebugIdentity\"], watch_0.debug_ops)\n\n # Verify debug URLs.\n self.assertEqual([\"file:///tmp/tfdbg_1\"], watch_0.debug_urls)\n\n def testAddDebugTensorWatches_multipleURLs(self):\n debug_utils.add_debug_tensor_watch(\n self._run_options,\n \"foo/node_a\",\n 0,\n debug_ops=\"DebugNanCount\",\n debug_urls=[\"file:///tmp/tfdbg_1\", \"file:///tmp/tfdbg_2\"])\n\n debug_watch_opts = self._run_options.debug_options.debug_tensor_watch_opts\n self.assertEqual(1, len(debug_watch_opts))\n\n watch_0 = debug_watch_opts[0]\n\n self.assertEqual(\"foo/node_a\", watch_0.node_name)\n self.assertEqual(0, watch_0.output_slot)\n\n # Verify default debug op name.\n self.assertEqual([\"DebugNanCount\"], watch_0.debug_ops)\n\n # Verify debug URLs.\n self.assertEqual([\"file:///tmp/tfdbg_1\", \"file:///tmp/tfdbg_2\"],\n watch_0.debug_urls)\n\n def testWatchGraph_allNodes(self):\n debug_utils.watch_graph(\n self._run_options,\n self._graph,\n debug_ops=[\"DebugIdentity\", \"DebugNanCount\"],\n debug_urls=\"file:///tmp/tfdbg_1\")\n\n debug_watch_opts = self._run_options.debug_options.debug_tensor_watch_opts\n self.assertEqual(self._expected_num_nodes, len(debug_watch_opts))\n\n # Verify that each of the nodes in the graph with output tensors in the\n # graph have debug tensor watch.\n node_names = self._verify_watches(debug_watch_opts, 0,\n [\"DebugIdentity\", \"DebugNanCount\"],\n [\"file:///tmp/tfdbg_1\"])\n\n # Verify the node names.\n self.assertTrue(\"a1_init\" in node_names)\n self.assertTrue(\"a1\" in node_names)\n self.assertTrue(\"a1/Assign\" in node_names)\n self.assertTrue(\"a1/read\" in node_names)\n\n self.assertTrue(\"b_init\" in node_names)\n self.assertTrue(\"b\" in node_names)\n self.assertTrue(\"b/Assign\" in node_names)\n self.assertTrue(\"b/read\" in node_names)\n\n self.assertTrue(\"c\" in node_names)\n self.assertTrue(\"p1\" in node_names)\n self.assertTrue(\"s\" in node_names)\n\n def testWatchGraph_nodeNameWhitelist(self):\n debug_utils.watch_graph(\n self._run_options,\n self._graph,\n debug_urls=\"file:///tmp/tfdbg_1\",\n node_name_regex_whitelist=\"(a1$|a1_init$|a1/.*|p1$)\")\n\n node_names = self._verify_watches(\n self._run_options.debug_options.debug_tensor_watch_opts, 0,\n [\"DebugIdentity\"], [\"file:///tmp/tfdbg_1\"])\n self.assertEqual(\n sorted([\"a1_init\", \"a1\", \"a1/Assign\", \"a1/read\", \"p1\"]),\n sorted(node_names))\n\n def testWatchGraph_opTypeWhitelist(self):\n debug_utils.watch_graph(\n self._run_options,\n self._graph,\n debug_urls=\"file:///tmp/tfdbg_1\",\n op_type_regex_whitelist=\"(Variable|MatMul)\")\n\n node_names = self._verify_watches(\n self._run_options.debug_options.debug_tensor_watch_opts, 0,\n [\"DebugIdentity\"], [\"file:///tmp/tfdbg_1\"])\n self.assertEqual(sorted([\"a1\", \"b\", \"p1\"]), sorted(node_names))\n\n def testWatchGraph_nodeNameAndOpTypeWhitelists(self):\n debug_utils.watch_graph(\n self._run_options,\n self._graph,\n debug_urls=\"file:///tmp/tfdbg_1\",\n node_name_regex_whitelist=\"([a-z]+1$)\",\n op_type_regex_whitelist=\"(MatMul)\")\n\n node_names = self._verify_watches(\n self._run_options.debug_options.debug_tensor_watch_opts, 0,\n [\"DebugIdentity\"], [\"file:///tmp/tfdbg_1\"])\n self.assertEqual([\"p1\"], node_names)\n\n def testWatchGraph_nodeNameBlacklist(self):\n debug_utils.watch_graph_with_blacklists(\n self._run_options,\n self._graph,\n debug_urls=\"file:///tmp/tfdbg_1\",\n node_name_regex_blacklist=\"(a1$|a1_init$|a1/.*|p1$)\")\n\n node_names = self._verify_watches(\n self._run_options.debug_options.debug_tensor_watch_opts, 0,\n [\"DebugIdentity\"], [\"file:///tmp/tfdbg_1\"])\n self.assertEqual(\n sorted([\"b_init\", \"b\", \"b/Assign\", \"b/read\", \"c\", \"s\"]),\n sorted(node_names))\n\n def testWatchGraph_opTypeBlacklist(self):\n debug_utils.watch_graph_with_blacklists(\n self._run_options,\n self._graph,\n debug_urls=\"file:///tmp/tfdbg_1\",\n op_type_regex_blacklist=\"(Variable|Identity|Assign|Const)\")\n\n node_names = self._verify_watches(\n self._run_options.debug_options.debug_tensor_watch_opts, 0,\n [\"DebugIdentity\"], [\"file:///tmp/tfdbg_1\"])\n self.assertEqual(sorted([\"p1\", \"s\"]), sorted(node_names))\n\n def testWatchGraph_nodeNameAndOpTypeBlacklists(self):\n debug_utils.watch_graph_with_blacklists(\n self._run_options,\n self._graph,\n debug_urls=\"file:///tmp/tfdbg_1\",\n node_name_regex_blacklist=\"p1$\",\n op_type_regex_blacklist=\"(Variable|Identity|Assign|Const)\")\n\n node_names = self._verify_watches(\n self._run_options.debug_options.debug_tensor_watch_opts, 0,\n [\"DebugIdentity\"], [\"file:///tmp/tfdbg_1\"])\n self.assertEqual([\"s\"], node_names)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"TensorFlow Ops for loss computation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.framework import deprecated\nfrom tensorflow.contrib.losses.python.losses import loss_ops\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops as array_ops_\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\n\n\n@deprecated('2016-12-01', 'Use `tf.contrib.losses.mean_squared_error` '\n 'and explicit logits computation.')\ndef mean_squared_error_regressor(tensor_in, labels, weights, biases, name=None):\n \"\"\"Returns prediction and loss for mean squared error regression.\"\"\"\n with ops.name_scope(name, 'mean_squared_error_regressor',\n [tensor_in, labels]):\n predictions = nn.xw_plus_b(tensor_in, weights, biases)\n if len(labels.get_shape()) == 1 and len(predictions.get_shape()) == 2:\n predictions = array_ops_.squeeze(predictions, squeeze_dims=[1])\n return predictions, loss_ops.mean_squared_error(predictions, labels)\n\n\n@deprecated('2016-12-01', 'Use `tf.contrib.losses.softmax_cross_entropy` '\n 'and explicit logits computation.')\ndef softmax_classifier(tensor_in,\n labels,\n weights,\n biases,\n class_weight=None,\n name=None):\n \"\"\"Returns prediction and loss for softmax classifier.\n\n This function returns \"probabilities\" and a cross entropy loss. To obtain\n predictions, use `tf.argmax` on the returned probabilities.\n\n This function requires labels to be passed in one-hot encoding.\n\n Args:\n tensor_in: Input tensor, [batch_size, feature_size], features.\n labels: Tensor, [batch_size, n_classes], one-hot labels of the output\n classes.\n weights: Tensor, [batch_size, feature_size], linear transformation\n matrix.\n biases: Tensor, [batch_size], biases.\n class_weight: Tensor, optional, [n_classes], weight for each class.\n If not given, all classes are supposed to have weight one.\n name: Operation name.\n\n Returns:\n `tuple` of softmax predictions and loss `Tensor`s.\n \"\"\"\n with ops.name_scope(name, 'softmax_classifier', [tensor_in, labels]):\n logits = nn.xw_plus_b(tensor_in, weights, biases)\n if class_weight is not None:\n logits = math_ops.mul(logits, class_weight)\n return nn.softmax(logits), loss_ops.softmax_cross_entropy(logits, labels)\n", "# Copyright 2016 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\"\"\"Keyword args tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.python.util import keyword_args\n\n\nclass KeywordArgsTest(tf.test.TestCase):\n\n def test_keyword_args_only(self):\n def func_without_decorator(a, b):\n return a+b\n\n @keyword_args.keyword_args_only\n def func_with_decorator(a, b):\n return func_without_decorator(a, b)\n\n self.assertEqual(3, func_without_decorator(1, 2))\n self.assertEqual(3, func_without_decorator(a=1, b=2))\n self.assertEqual(3, func_with_decorator(a=1, b=2))\n\n # Providing non-keyword args should fail.\n with self.assertRaisesRegexp(\n ValueError, \"Must use keyword args to call func_with_decorator.\"):\n self.assertEqual(3, func_with_decorator(1, 2))\n\n # Partially providing keyword args should fail.\n with self.assertRaisesRegexp(\n ValueError, \"Must use keyword args to call func_with_decorator.\"):\n self.assertEqual(3, func_with_decorator(1, b=2))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# 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# ==============================================================================\n\n\"\"\"Tests for SparseTensorsMap.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import sparse_ops\n\n# pylint: disable=protected-access\nadd_sparse_to_tensors_map = sparse_ops._add_sparse_to_tensors_map\nadd_many_sparse_to_tensors_map = sparse_ops._add_many_sparse_to_tensors_map\ntake_many_sparse_from_tensors_map = (\n sparse_ops._take_many_sparse_from_tensors_map)\n# pylint: enable=protected-access\n\n\nclass SparseTensorsMapTest(tf.test.TestCase):\n\n def _SparseTensorPlaceholder(self, dtype=None):\n if dtype is None: dtype = tf.int32\n return tf.SparseTensor(\n tf.placeholder(tf.int64),\n tf.placeholder(dtype),\n tf.placeholder(tf.int64))\n\n def _SparseTensorValue_5x6(self, permutation):\n ind = np.array([\n [0, 0],\n [1, 0], [1, 3], [1, 4],\n [3, 2], [3, 3]]).astype(np.int64)\n val = np.array([0, 10, 13, 14, 32, 33]).astype(np.int32)\n\n ind = ind[permutation]\n val = val[permutation]\n\n shape = np.array([5, 6]).astype(np.int64)\n return tf.SparseTensorValue(ind, val, shape)\n\n def _SparseTensorValue_3x4(self, permutation):\n ind = np.array([\n [0, 0],\n [1, 0], [1, 2], [1, 3],\n [2, 2], [2, 3]]).astype(np.int64)\n val = np.array([0, 10, 13, 14, 32, 33]).astype(np.int32)\n\n ind = ind[permutation]\n val = val[permutation]\n\n shape = np.array([3, 4]).astype(np.int64)\n return tf.SparseTensorValue(ind, val, shape)\n\n def _SparseTensorValue_1x1x1(self):\n ind = np.array([[0, 0, 0]]).astype(np.int64)\n val = np.array([0]).astype(np.int32)\n shape = np.array([3, 4, 5]).astype(np.int64)\n return tf.SparseTensorValue(ind, val, shape)\n\n def testAddTakeMany(self):\n with self.test_session(graph=tf.Graph(), use_gpu=False) as sess:\n sp_input0 = self._SparseTensorValue_5x6(np.arange(6))\n sp_input1 = self._SparseTensorValue_3x4(np.arange(6))\n handle0 = add_sparse_to_tensors_map(sp_input0, shared_name=\"a\")\n handle1 = add_sparse_to_tensors_map(sp_input1, shared_name=\"a\")\n self.assertEqual(handle0.get_shape(), ())\n handles_concat = tf.stack([handle0, handle1])\n\n sp_out = take_many_sparse_from_tensors_map(\n sparse_map_op=handle0.op, sparse_handles=handles_concat)\n\n combined_indices, combined_values, combined_shape = sess.run(sp_out)\n\n self.assertAllEqual(combined_indices[:6, 0], [0] * 6) # minibatch 0\n self.assertAllEqual(combined_indices[:6, 1:], sp_input0[0])\n self.assertAllEqual(combined_indices[6:, 0], [1] * 6) # minibatch 1\n self.assertAllEqual(combined_indices[6:, 1:], sp_input1[0])\n self.assertAllEqual(combined_values[:6], sp_input0[1])\n self.assertAllEqual(combined_values[6:], sp_input1[1])\n self.assertAllEqual(combined_shape, [2, 5, 6])\n\n def testFeedAddTakeMany(self):\n with self.test_session(use_gpu=False) as sess:\n sp_input = self._SparseTensorPlaceholder()\n input0_val = self._SparseTensorValue_5x6(np.arange(6))\n input1_val = self._SparseTensorValue_3x4(np.arange(6))\n handle = add_sparse_to_tensors_map(sp_input)\n\n handle0_value = sess.run(\n handle, feed_dict={sp_input: input0_val})\n handle1_value = sess.run(\n handle, feed_dict={sp_input: input1_val})\n\n sparse_handles = tf.convert_to_tensor(\n [handle0_value, handle1_value], dtype=tf.int64)\n\n sp_roundtrip = take_many_sparse_from_tensors_map(\n sparse_map_op=handle.op, sparse_handles=sparse_handles)\n\n combined_indices, combined_values, combined_shape = sess.run(\n sp_roundtrip)\n\n self.assertAllEqual(combined_indices[:6, 0], [0] * 6) # minibatch 0\n self.assertAllEqual(combined_indices[:6, 1:], input0_val[0])\n self.assertAllEqual(combined_indices[6:, 0], [1] * 6) # minibatch 1\n self.assertAllEqual(combined_indices[6:, 1:], input1_val[0])\n self.assertAllEqual(combined_values[:6], input0_val[1])\n self.assertAllEqual(combined_values[6:], input1_val[1])\n self.assertAllEqual(combined_shape, [2, 5, 6])\n\n def testAddManyTakeManyRoundTrip(self):\n with self.test_session(use_gpu=False) as sess:\n # N == 4 because shape_value == [4, 5]\n indices_value = np.array([[0, 0], [0, 1], [2, 0]], dtype=np.int64)\n values_value = np.array([b\"a\", b\"b\", b\"c\"])\n shape_value = np.array([4, 5], dtype=np.int64)\n sparse_tensor = self._SparseTensorPlaceholder(dtype=tf.string)\n handles = add_many_sparse_to_tensors_map(sparse_tensor)\n roundtrip = take_many_sparse_from_tensors_map(\n sparse_map_op=handles.op, sparse_handles=handles)\n handles_value, roundtrip_value = sess.run(\n [handles, roundtrip],\n feed_dict={sparse_tensor.indices: indices_value,\n sparse_tensor.values: values_value,\n sparse_tensor.dense_shape: shape_value})\n self.assertEqual(handles_value.shape, (4,))\n self.assertAllEqual(roundtrip_value.indices, indices_value)\n self.assertAllEqual(roundtrip_value.values, values_value)\n self.assertAllEqual(roundtrip_value.dense_shape, shape_value)\n\n def testDeserializeFailsInconsistentRank(self):\n with self.test_session(use_gpu=False) as sess:\n sp_input = self._SparseTensorPlaceholder()\n input0_val = self._SparseTensorValue_5x6(np.arange(6))\n input1_val = self._SparseTensorValue_1x1x1()\n handle = add_sparse_to_tensors_map(sp_input)\n\n handle0_value = sess.run(\n handle, feed_dict={sp_input: input0_val})\n handle1_value = sess.run(\n handle, feed_dict={sp_input: input1_val})\n\n handle_concat = tf.convert_to_tensor(\n [handle0_value, handle1_value], dtype=tf.int64)\n\n sp_roundtrip = take_many_sparse_from_tensors_map(\n sparse_map_op=handle.op, sparse_handles=handle_concat)\n\n with self.assertRaisesOpError(\n r\"Inconsistent rank across SparseTensors: rank prior to \"\n r\"SparseTensor\\[1\\] was: 3 but rank of SparseTensor\\[1\\] is: 4\"):\n sess.run(sp_roundtrip)\n\n def testTakeManyFailsWrongInputOp(self):\n with self.test_session(use_gpu=False) as sess:\n input_val = self._SparseTensorValue_5x6(np.arange(6))\n handle = add_sparse_to_tensors_map(input_val)\n handle_value = sess.run(handle)\n bad_handle = handle_value + 10\n sp_roundtrip = take_many_sparse_from_tensors_map(\n sparse_map_op=handle.op,\n sparse_handles=[handle_value, bad_handle])\n\n with self.assertRaisesOpError(r\"Unable to find SparseTensor: 10\"):\n sess.run(sp_roundtrip)\n\n\nclass BenchmarkSparseTensorsMapVsSerialization(tf.test.Benchmark):\n\n def benchmarkVeryLarge2DFloatSparseTensor(self):\n np.random.seed(127)\n num_elements = 10000\n batch_size = 64\n indices_batch = np.random.randint(\n batch_size, size=num_elements, dtype=np.int64)\n indices_value = np.arange(num_elements, dtype=np.int64)\n indices = np.asarray(\n sorted(zip(indices_batch, indices_value)), dtype=np.int64)\n values = [\"feature_value_for_embedding_lookup\"] * num_elements\n shape = np.asarray([batch_size, num_elements], dtype=np.int64)\n with tf.Session() as sess:\n with tf.device(\"/cpu:0\"):\n indices = tf.Variable(indices)\n values = tf.Variable(values)\n shape = tf.Variable(shape)\n st = tf.SparseTensor(indices, values, shape)\n\n st_handles = add_many_sparse_to_tensors_map(st)\n st_roundtrip = take_many_sparse_from_tensors_map(\n sparse_map_op=st_handles.op, sparse_handles=st_handles)\n st_roundtrip_op = st_roundtrip.values.op\n\n st_serialized = tf.serialize_many_sparse(st)\n st_deserialized = tf.deserialize_many_sparse(\n st_serialized, dtype=values.dtype)\n st_deserialized_op = st_deserialized.values.op\n\n tf.global_variables_initializer().run()\n\n st_roundtrip_values = sess.run(st_roundtrip)\n st_deserialized_values = sess.run(st_deserialized)\n np.testing.assert_equal(\n st_roundtrip_values.values, st_deserialized_values.values)\n np.testing.assert_equal(\n st_roundtrip_values.indices, st_deserialized_values.indices)\n np.testing.assert_equal(\n st_roundtrip_values.dense_shape, st_deserialized_values.dense_shape)\n\n self.run_op_benchmark(\n sess, st_roundtrip_op, min_iters=2000,\n name=\"benchmark_very_large_2d_float_st_tensor_maps\")\n self.run_op_benchmark(\n sess, st_deserialized_op, min_iters=2000,\n name=\"benchmark_very_large_2d_float_st_serialization\")\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n# ==============================================================================\n\n\"\"\"Tests for clustering_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n# pylint: disable=unused-import\nimport tensorflow as tf\n# pylint: enable=unused-import\n\n\nclass KmeansPlusPlusInitializationTest(tf.test.TestCase):\n\n # All but one input point are close to (101, 1). With uniform random sampling,\n # it is highly improbable for (-1, -1) to be selected.\n def setUp(self):\n self._points = np.array([\n [100., 0.],\n [101., 2.],\n [102., 0.],\n [100., 1.],\n [100., 2.],\n [101., 0.],\n [101., 0.],\n [101., 1.],\n [102., 0.],\n [-1., -1.]\n ]).astype(np.float32)\n\n def runTestWithSeed(self, seed):\n with self.test_session():\n sampled_points = tf.contrib.factorization.kmeans_plus_plus_initialization(\n self._points, 3, seed, (seed % 5) - 1)\n self.assertAllClose(sorted(sampled_points.eval().tolist()), [\n [-1., -1.],\n [101., 1.],\n [101., 1.]\n ], atol=1.0)\n\n def testBasic(self):\n for seed in range(100):\n self.runTestWithSeed(seed)\n\n\n# A simple test that can be verified by hand.\nclass NearestCentersTest(tf.test.TestCase):\n\n def setUp(self):\n self._points = np.array([\n [100., 0.],\n [101., 2.],\n [99., 2.],\n [1., 1.]\n ]).astype(np.float32)\n\n self._centers = np.array([\n [100., 0.],\n [99., 1.],\n [50., 50.],\n [0., 0.],\n [1., 1.]\n ]).astype(np.float32)\n\n def testNearest1(self):\n with self.test_session():\n [indices, distances] = tf.contrib.factorization.nearest_neighbors(\n self._points, self._centers, 1)\n self.assertAllClose(indices.eval(), [[0], [0], [1], [4]])\n self.assertAllClose(distances.eval(), [[0.], [5.], [1.], [0.]])\n\n def testNearest2(self):\n with self.test_session():\n [indices, distances] = tf.contrib.factorization.nearest_neighbors(\n self._points, self._centers, 2)\n self.assertAllClose(indices.eval(),\n [[0, 1], [0, 1], [1, 0], [4, 3]])\n self.assertAllClose(distances.eval(),\n [[0., 2.], [5., 5.], [1., 5.], [0., 2.]])\n\n\n# A test with large inputs.\nclass NearestCentersLargeTest(tf.test.TestCase):\n\n def setUp(self):\n num_points = 1000\n num_centers = 2000\n num_dim = 100\n max_k = 5\n # Construct a small number of random points and later tile them.\n points_per_tile = 10\n assert num_points % points_per_tile == 0\n points = np.random.standard_normal([points_per_tile, num_dim]).astype(\n np.float32)\n # Construct random centers.\n self._centers = np.random.standard_normal([num_centers, num_dim]).astype(\n np.float32)\n # Exhaustively compute expected nearest neighbors.\n def squared_distance(x, y):\n return np.linalg.norm(x - y, ord=2) ** 2\n nearest_neighbors = [sorted([(squared_distance(point, self._centers[j]), j)\n for j in range(num_centers)])[:max_k]\n for point in points]\n expected_nearest_neighbor_indices = np.array(\n [[i for _, i in nn] for nn in nearest_neighbors])\n expected_nearest_neighbor_squared_distances = np.array(\n [[dist for dist, _ in nn] for nn in nearest_neighbors])\n # Tile points and expected results to reach requested size (num_points)\n (self._points,\n self._expected_nearest_neighbor_indices,\n self._expected_nearest_neighbor_squared_distances) = (\n np.tile(x, (num_points / points_per_tile, 1))\n for x in (points,\n expected_nearest_neighbor_indices,\n expected_nearest_neighbor_squared_distances))\n\n def testNearest1(self):\n with self.test_session():\n [indices, distances] = tf.contrib.factorization.nearest_neighbors(\n self._points, self._centers, 1)\n self.assertAllClose(indices.eval(),\n self._expected_nearest_neighbor_indices[:, [0]])\n self.assertAllClose(\n distances.eval(),\n self._expected_nearest_neighbor_squared_distances[:, [0]])\n\n def testNearest5(self):\n with self.test_session():\n [indices, distances] = tf.contrib.factorization.nearest_neighbors(\n self._points, self._centers, 5)\n self.assertAllClose(indices.eval(),\n self._expected_nearest_neighbor_indices[:, 0:5])\n self.assertAllClose(\n distances.eval(),\n self._expected_nearest_neighbor_squared_distances[:, 0:5])\n\n\nif __name__ == '__main__':\n np.random.seed(0)\n tf.test.main()\n", "# Copyright 2016 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\"\"\"Tests for ParameterizedTruncatedNormalOp.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport math\nimport timeit\n\nimport numpy as np\nfrom six.moves import range # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import random_ops\n\n\nclass TruncatedNormalMoments(object):\n memoized_moments = None\n mean = None\n stddev = None\n minval = None\n maxval = None\n\n def __init__(self, mean, stddev, minval, maxval):\n self.memoized_moments = [1.0] # 0th moment\n self.mean = np.double(mean)\n self.stddev = np.double(stddev)\n # NOTE(ringwalt): The formula doesn't handle infinite values.\n self.minval = np.double(max(-10, minval))\n self.maxval = np.double(min(10, maxval))\n\n def __getitem__(self, moment):\n \"\"\"Calculates the truncated normal moments.\n\n Args:\n moment: The number for the moment.\n\n Returns:\n The value for the given moment.\n\n Uses the recurrence relation described in:\n http://www.smp.uq.edu.au/people/YoniNazarathy/teaching_projects\n /studentWork/EricOrjebin_TruncatedNormalMoments.pdf\n \"\"\"\n assert moment > 0\n # The test case must ensure it can import scipy.stats before this point.\n import scipy.stats # pylint: disable=g-import-not-at-top\n dist = scipy.stats.norm(loc=self.mean, scale=self.stddev)\n for k in range(len(self.memoized_moments), moment + 1):\n m_k_minus_2 = self.memoized_moments[k - 2] if k > 1 else np.double(0.0)\n m_k_minus_1 = self.memoized_moments[k - 1]\n numerator = (np.power(self.maxval, k - 1) * dist.pdf(self.maxval) -\n np.power(self.minval, k - 1) * dist.pdf(self.minval))\n denominator = dist.cdf(self.maxval) - dist.cdf(self.minval)\n m = ((k - 1) * self.stddev**2 * m_k_minus_2 + self.mean * m_k_minus_1 -\n self.stddev * numerator / denominator)\n assert abs(m) < 1e50 # ensure numerical accuracy\n self.memoized_moments.append(m)\n return self.memoized_moments[moment]\n\n\ndef calculate_moments(samples, max_moment):\n moments = [0.0] * (max_moment + 1)\n for sample in samples:\n value = 1.0\n for k in range(len(moments)):\n moments[k] += value\n value *= sample\n for i in range(len(moments)):\n moments[i] /= len(samples)\n return moments\n\n\ndef z_test(real, expected, i, num_samples):\n numerical_error = 1e-6 # per-operation error\n moment_mean = expected[i]\n moment_squared = expected[2 * i]\n moment_var = moment_squared - moment_mean * moment_mean\n\n error_per_moment = i * numerical_error\n total_variance = moment_var / float(num_samples) + error_per_moment\n return abs((real[i] - moment_mean) / math.sqrt(total_variance))\n\n\nclass ParameterizedTruncatedNormalTest(tf.test.TestCase):\n _use_gpu = False\n z_limit = 6.0\n\n # Stop at moment 10 to avoid numerical errors in the theoretical moments.\n max_moment = 10\n\n def validateMoments(self, shape, mean, stddev, minval, maxval, seed=1618):\n try:\n # TruncatedNormalMoments requires scipy.stats.\n # Give up early if we are unable to import it.\n import scipy.stats # pylint: disable=g-import-not-at-top,unused-variable\n tf.set_random_seed(seed)\n with self.test_session(use_gpu=self._use_gpu):\n samples = random_ops.parameterized_truncated_normal(shape, mean, stddev,\n minval,\n maxval).eval()\n assert (~np.isnan(samples)).all()\n moments = calculate_moments(samples, self.max_moment)\n expected_moments = TruncatedNormalMoments(mean, stddev, minval, maxval)\n num_samples = functools.reduce(lambda x, y: x * y, shape, 1)\n for i in range(1, len(moments)):\n self.assertLess(\n z_test(moments, expected_moments, i, num_samples), self.z_limit)\n except ImportError as e:\n tf.logging.warn(\"Cannot test truncated normal op: %s\" % str(e))\n\n def validateKolmogorovSmirnov(self,\n shape,\n mean,\n stddev,\n minval,\n maxval,\n seed=1618):\n try:\n import scipy.stats # pylint: disable=g-import-not-at-top\n tf.set_random_seed(seed)\n with self.test_session(use_gpu=self._use_gpu):\n samples = random_ops.parameterized_truncated_normal(shape, mean, stddev,\n minval,\n maxval).eval()\n assert (~np.isnan(samples)).all()\n minval = max(mean - stddev * 10, minval)\n maxval = min(mean + stddev * 10, maxval)\n dist = scipy.stats.norm(loc=mean, scale=stddev)\n cdf_min = dist.cdf(minval)\n cdf_max = dist.cdf(maxval)\n\n def truncated_cdf(x):\n return np.clip((dist.cdf(x) - cdf_min) / (cdf_max - cdf_min), 0.0, 1.0)\n\n pvalue = scipy.stats.kstest(samples, truncated_cdf)[1]\n self.assertGreater(pvalue, 1e-10)\n except ImportError as e:\n tf.logging.warn(\"Cannot test truncated normal op: %s\" % str(e))\n\n def testDefaults(self):\n self.validateMoments([10**5], 0.0, 1.0, -2.0, 2.0)\n\n def testShifted(self):\n self.validateMoments([10**5], -1.0, 1.0, -2.0, 2.0)\n\n def testRightTail(self):\n self.validateMoments([10**5], 0.0, 1.0, 4.0, np.infty)\n\n def testLeftTail(self):\n self.validateMoments([10**5], 0.0, 1.0, -np.infty, -4.0)\n\n def testLeftTailTwoSidedBounds(self):\n self.validateMoments([10**5], 0.0, 1.0, -6.0, -3.0)\n\n def testTwoSidedLeftTailShifted(self):\n self.validateKolmogorovSmirnov([10**5], 6.0, 1.0, -1.0, 1.0)\n\n def testRightTailShifted(self):\n self.validateMoments([10**5], -5.0, 1.0, 2.0, np.infty)\n\n def testSmallStddev(self):\n self.validateKolmogorovSmirnov([10**5], 0.0, 0.1, 0.05, 0.10)\n\n\nclass ParameterizedTruncatedNormalGpuTest(ParameterizedTruncatedNormalTest):\n _use_gpu = True\n\n\n# Benchmarking code\ndef parameterized_vs_naive(shape, num_iters, use_gpu=False):\n np.random.seed(1618) # Make it reproducible.\n\n # No CSE/CF.\n optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)\n config = tf.ConfigProto(\n graph_options=tf.GraphOptions(optimizer_options=optimizer_options))\n\n with tf.Session(config=config) as sess:\n with tf.device(\"/cpu:0\" if not use_gpu else None):\n param_op = tf.group(random_ops.parameterized_truncated_normal(shape))\n naive_op = tf.group(random_ops.truncated_normal(shape))\n\n # Burn-in to avoid session setup costs in the timing.\n sess.run(param_op)\n sess.run(param_op)\n param_dt = timeit.timeit(lambda: sess.run(param_op), number=num_iters)\n sess.run(naive_op)\n sess.run(naive_op)\n naive_dt = timeit.timeit(lambda: sess.run(naive_op), number=num_iters)\n return param_dt, naive_dt\n\n\nclass TruncatedNormalBenchmark(tf.test.Benchmark):\n\n def benchmarkParameterizedOpVsNaiveOpCpu(self):\n self._benchmarkParameterizedOpVsNaiveOp(False)\n\n def benchmarkParameterizedOpVsNaiveOpGpu(self):\n self._benchmarkParameterizedOpVsNaiveOp(True)\n\n def _benchmarkParameterizedOpVsNaiveOp(self, use_gpu):\n num_iters = 50\n print((\"Composition of new ParameterizedTruncatedNormalOp vs. \"\n \"naive TruncatedNormalOp [%d iters]\") % num_iters)\n print(\"Shape\\tsec(parameterized)\\tsec(naive)\\tspeedup\")\n\n for shape in [[10000, 100], [1000, 1000], [1000000], [100, 100, 100],\n [20, 20, 20, 20]]:\n p_dt, n_dt = parameterized_vs_naive(shape, num_iters, use_gpu)\n print(\"%s\\t%.3f\\t%.3f\\t%.2f\" % (shape, p_dt, n_dt, p_dt / n_dt))\n\n shape_str = \"-\".join(map(str, shape))\n self.report_benchmark(\n name=\"parameterized_shape\" + shape_str,\n iters=num_iters,\n wall_time=p_dt)\n self.report_benchmark(\n name=\"naive_shape\" + shape_str, iters=num_iters, wall_time=n_dt)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2016 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\"\"\"Tests for Python ops defined in math_grad.py.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass SquaredDifferenceOpTest(tf.test.TestCase):\n\n def _testGrad(self, left_shape, right_shape):\n\n if len(left_shape) > len(right_shape):\n output_shape = left_shape\n else:\n output_shape = right_shape\n l = np.random.randn(*left_shape)\n r = np.random.randn(*right_shape)\n\n with self.test_session(use_gpu=True):\n left_tensor = tf.constant(l, shape=left_shape)\n right_tensor = tf.constant(r, shape=right_shape)\n output = tf.squared_difference(left_tensor, right_tensor)\n left_err = tf.test.compute_gradient_error(left_tensor,\n left_shape,\n output,\n output_shape,\n x_init_value=l)\n right_err = tf.test.compute_gradient_error(right_tensor,\n right_shape,\n output,\n output_shape,\n x_init_value=r)\n self.assertLess(left_err, 1e-10)\n self.assertLess(right_err, 1e-10)\n\n def testGrad(self):\n self._testGrad([1, 2, 3, 2], [3, 2])\n self._testGrad([2, 4], [3, 2, 4])\n\n\nclass AbsOpTest(tf.test.TestCase):\n\n def _biasedRandN(self, shape, bias=0.1, sigma=1.0):\n \"\"\"Returns samples from a normal distribution shifted `bias` away from 0.\"\"\"\n value = np.random.randn(*shape) * sigma\n return value + np.sign(value) * bias\n\n def _testGrad(self, shape, dtype=None, max_error=None, bias=None, sigma=None):\n np.random.seed(7)\n if dtype in (tf.complex64, tf.complex128):\n value = tf.complex(self._biasedRandN(shape, bias=bias, sigma=sigma),\n self._biasedRandN(shape, bias=bias, sigma=sigma))\n else:\n value = tf.convert_to_tensor(self._biasedRandN(shape, bias=bias),\n dtype=dtype)\n\n with self.test_session(use_gpu=True):\n if dtype in (tf.complex64, tf.complex128):\n output = tf.complex_abs(value)\n else:\n output = tf.abs(value)\n error = tf.test.compute_gradient_error(\n value, shape, output, output.get_shape().as_list())\n self.assertLess(error, max_error)\n\n def testComplexAbs(self):\n # Bias random test values away from zero to avoid numeric instabilities.\n self._testGrad([3, 3], dtype=tf.float32, max_error=2e-5, bias=0.1,\n sigma=1.0)\n self._testGrad([3, 3], dtype=tf.complex64, max_error=2e-5, bias=0.1,\n sigma=1.0)\n\n # Ensure stability near the pole at zero.\n self._testGrad([3, 3], dtype=tf.float32, max_error=100.0, bias=0.0,\n sigma=0.1)\n self._testGrad([3, 3], dtype=tf.complex64, max_error=100.0, bias=0.0,\n sigma=0.1)\n\n\nclass MinOrMaxGradientTest(tf.test.TestCase):\n\n def testMinGradient(self):\n inputs = tf.constant([1.0], dtype=tf.float32)\n outputs = tf.reduce_min(tf.concat_v2([inputs, inputs], 0))\n with self.test_session():\n error = tf.test.compute_gradient_error(inputs, [1], outputs, [])\n self.assertLess(error, 1e-4)\n\n def testMaxGradient(self):\n inputs = tf.constant([1.0], dtype=tf.float32)\n outputs = tf.reduce_max(tf.concat_v2([inputs, inputs], 0))\n with self.test_session():\n error = tf.test.compute_gradient_error(inputs, [1], outputs, [])\n self.assertLess(error, 1e-4)\n\n\nclass SegmentMinOrMaxGradientTest(tf.test.TestCase):\n\n def testSegmentMinGradient(self):\n data = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32)\n segment_ids = tf.constant([0, 0, 1], dtype=tf.int64)\n segment_min = tf.segment_min(data, segment_ids)\n with self.test_session():\n error = tf.test.compute_gradient_error(data, [3], segment_min, [2])\n self.assertLess(error, 1e-4)\n\n def testSegmentMaxGradient(self):\n data = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32)\n segment_ids = tf.constant([0, 0, 1], dtype=tf.int64)\n segment_max = tf.segment_max(data, segment_ids)\n with self.test_session():\n error = tf.test.compute_gradient_error(data, [3], segment_max, [2])\n self.assertLess(error, 1e-4)\n\n def testSegmentMinGradientWithTies(self):\n inputs = tf.constant([1.0], dtype=tf.float32)\n data = tf.concat_v2([inputs, inputs], 0)\n segment_ids = tf.constant([0, 0], dtype=tf.int64)\n segment_min = tf.segment_min(data, segment_ids)\n with self.test_session():\n error = tf.test.compute_gradient_error(inputs, [1], segment_min, [1])\n self.assertLess(error, 1e-4)\n\n def testSegmentMaxGradientWithTies(self):\n inputs = tf.constant([1.0], dtype=tf.float32)\n data = tf.concat_v2([inputs, inputs], 0)\n segment_ids = tf.constant([0, 0], dtype=tf.int64)\n segment_max = tf.segment_max(data, segment_ids)\n with self.test_session():\n error = tf.test.compute_gradient_error(inputs, [1], segment_max, [1])\n self.assertLess(error, 1e-4)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2016 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\"\"\"The metric spec class to flexibly connect models and metrics.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.platform import tf_logging as logging\n\n\nclass MetricSpec(object):\n \"\"\"MetricSpec connects a model to metric functions.\n\n The MetricSpec class contains all information necessary to connect the\n output of a `model_fn` to the metrics (usually, streaming metrics) that are\n used in evaluation.\n\n It is passed in the `metrics` argument of `Estimator.evaluate`. The\n `Estimator` then knows which predictions, labels, and weight to use to call a\n given metric function.\n\n When building the ops to run in evaluation, `Estimator` will call\n `create_metric_ops`, which will connect the given `metric_fn` to the model\n as detailed in the docstring for `create_metric_ops`, and return the metric.\n\n Example:\n\n Assuming a model has an input function which returns inputs containing\n (among other things) a tensor with key \"input_key\", and a labels dictionary\n containing \"label_key\". Let's assume that the `model_fn` for this model\n returns a prediction with key \"prediction_key\".\n\n In order to compute the accuracy of the \"prediction_key\" prediction, we\n would add\n\n ```\n \"prediction accuracy\": MetricSpec(metric_fn=prediction_accuracy_fn,\n prediction_key=\"prediction_key\",\n label_key=\"label_key\")\n ```\n\n to the metrics argument to `evaluate`. `prediction_accuracy_fn` can be either\n a predefined function in metric_ops (e.g., `streaming_accuracy`) or a custom\n function you define.\n\n If we would like the accuracy to be weighted by \"input_key\", we can add that\n as the `weight_key` argument.\n\n ```\n \"prediction accuracy\": MetricSpec(metric_fn=prediction_accuracy_fn,\n prediction_key=\"prediction_key\",\n label_key=\"label_key\",\n weight_key=\"input_key\")\n ```\n\n An end-to-end example is as follows:\n\n ```\n estimator = tf.contrib.learn.Estimator(...)\n estimator.fit(...)\n _ = estimator.evaluate(\n input_fn=input_fn,\n steps=1,\n metrics={\n 'prediction accuracy':\n metric_spec.MetricSpec(\n metric_fn=prediction_accuracy_fn,\n prediction_key=\"prediction_key\",\n label_key=\"label_key\")\n })\n ```\n\n \"\"\"\n\n def __init__(self,\n metric_fn,\n prediction_key=None,\n label_key=None,\n weight_key=None):\n \"\"\"Constructor.\n\n Creates a MetricSpec.\n\n Args:\n metric_fn: A function to use as a metric. Must accept `predictions`,\n `labels` and optionally, `weights` tensors as inputs, and must return\n either a single tensor which is interpreted as a value of this metric,\n or a pair `(value_op, update_op)`, where value_op is the op to call to\n obtain the value of the metric, and update_op should be evaluated for\n each batch in order to update internal state.\n prediction_key: The key for a tensor in the `predictions` dict (output\n from the `model_fn`) to use as the `predictions` input to the\n `metric_fn`. Optional. If `None`, the `model_fn` must return a single\n tensor or a dict with only a single entry as `predictions`.\n label_key: The key for a tensor in the `labels` dict (output from the\n `input_fn`) to use as the `labels` input to the `metric_fn`.\n Optional. If `None`, the `input_fn` must return a single tensor or a\n dict with only a single entry as `labels`.\n weight_key: The key for a tensor in the `inputs` dict (output from the\n `input_fn`) to use as the `weights` input to the `metric_fn`.\n Optional. If `None`, no weights will be passed to the `metric_fn`.\n \"\"\"\n self._metric_fn = metric_fn\n self._prediction_key = prediction_key\n self._label_key = label_key\n self._weight_key = weight_key\n\n @property\n def prediction_key(self):\n return self._prediction_key\n\n @property\n def label_key(self):\n return self._label_key\n\n @property\n def weight_key(self):\n return self._weight_key\n\n @property\n def metric_fn(self):\n return self._metric_fn\n\n def __str__(self):\n if hasattr(self.metric_fn, '__name__'):\n fn_name = self.metric_fn.__name__\n elif (hasattr(self.metric_fn, 'func') and\n hasattr(self.metric_fn.func, '__name__')):\n fn_name = self.metric_fn.func.__name__ # If it's a functools.partial.\n else:\n fn_name = '%s' % self.metric_fn\n\n return ('MetricSpec(metric_fn=%s, ' % fn_name +\n 'prediction_key=%s, ' % self.prediction_key +\n 'label_key=%s, ' % self.label_key +\n 'weight_key=%s)' % self.weight_key\n )\n\n def create_metric_ops(self, inputs, labels, predictions):\n \"\"\"Connect our `metric_fn` to the specified members of the given dicts.\n\n This function will call the `metric_fn` given in our constructor as follows:\n\n ```\n metric_fn(predictions[self.prediction_key],\n labels[self.label_key],\n weights=weights[self.weight_key])\n ```\n\n And returns the result. The `weights` argument is only passed if\n `self.weight_key` is not `None`.\n\n `predictions` and `labels` may be single tensors as well as dicts. If\n `predictions` is a single tensor, `self.prediction_key` must be `None`. If\n `predictions` is a single element dict, `self.prediction_key` is allowed to\n be `None`. Conversely, if `labels` is a single tensor, `self.label_key` must\n be `None`. If `labels` is a single element dict, `self.label_key` is allowed\n to be `None`.\n\n Args:\n inputs: A dict of inputs produced by the `input_fn`\n labels: A dict of labels or a single label tensor produced by the\n `input_fn`.\n predictions: A dict of predictions or a single tensor produced by the\n `model_fn`.\n\n Returns:\n The result of calling `metric_fn`.\n\n Raises:\n ValueError: If `predictions` or `labels` is a single `Tensor` and\n `self.prediction_key` or `self.label_key` is not `None`; or if\n `self.label_key` is `None` but `labels` is a dict with more than one\n element, or if `self.prediction_key` is `None but `predictions` is a\n dict with more than one element.\n \"\"\"\n def _get_dict(name, dict_or_tensor, key):\n \"\"\"Get a single tensor or an element of a dict or raise ValueError.\"\"\"\n if key:\n if not isinstance(dict_or_tensor, dict):\n raise ValueError('MetricSpec with ' + name + '_key specified'\n ' requires ' +\n name + 's dict, got %s' % dict_or_tensor)\n if key not in dict_or_tensor:\n raise KeyError(\n 'Key \\'%s\\' missing from %s.' % (key, dict_or_tensor.keys()))\n return dict_or_tensor[key]\n else:\n if isinstance(dict_or_tensor, dict):\n if len(dict_or_tensor) != 1:\n raise ValueError('MetricSpec without specified ' + name + '_key'\n ' requires ' + name + 's tensor or single element'\n ' dict, got %s' % dict_or_tensor)\n return dict_or_tensor.values()[0]\n else:\n return dict_or_tensor\n\n # Get the predictions\n prediction = _get_dict('prediction', predictions, self.prediction_key)\n\n # Get the labels\n label = _get_dict('label', labels, self.label_key)\n\n try:\n if self.weight_key:\n return self.metric_fn(prediction, label,\n weights=inputs[self.weight_key])\n else:\n return self.metric_fn(prediction, label)\n except: # pylint: disable=bare-except\n logging.error('Could not create metric ops for %s.' % self)\n raise\n" ]
[ [ "tensorflow.constant", "tensorflow.contrib.seq2seq.simple_decoder_fn_inference", "tensorflow.contrib.layers.linear", "tensorflow.contrib.seq2seq.dynamic_rnn_decoder", "tensorflow.test.main", "tensorflow.constant_initializer", "tensorflow.global_variables_initializer", "tensorflow.contrib.seq2seq.simple_decoder_fn_train", "tensorflow.variable_scope", "tensorflow.nn.rnn_cell.GRUCell", "tensorflow.random_normal_initializer" ], [ "tensorflow.device", "tensorflow.Variable", "tensorflow.test.main", "tensorflow.train.ClusterSpec", "tensorflow.train.replica_device_setter" ], [ "tensorflow.python.framework.ops.NotDifferentiable", "tensorflow.python.ops.sparse_ops.sparse_merge", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.array_ops.slice", "tensorflow.python.framework.tensor_shape.as_shape", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.gen_parsing_ops._parse_example", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.gen_parsing_ops._parse_single_sequence_example" ], [ "tensorflow.core.util.test_log_pb2.TestResults", "tensorflow.core.util.test_log_pb2.BenchmarkEntries", "tensorflow.gfile.DeleteRecursively", "tensorflow.gfile.Exists", "tensorflow.gfile.GFile", "tensorflow.tools.test.system_info_lib.gather_machine_configuration" ], [ "tensorflow.tensorboard.backend.handler._uniform_sample", "tensorflow.python.platform.googletest.main" ], [ "tensorflow.test.compute_gradient_error", "tensorflow.constant", "tensorflow.nn.pool", "tensorflow.test.main", "numpy.prod", "tensorflow.test.is_gpu_available", "numpy.array", "numpy.zeros" ], [ "tensorflow.contrib.distributions.python.ops.logistic._Logistic", "tensorflow.python.ops.math_ops.log", "tensorflow.python.ops.check_ops.assert_positive", "tensorflow.contrib.distributions.python.ops.distribution_util.get_logits_and_prob", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.array_ops.identity" ], [ "tensorflow.python.platform.tf_logging.debug", "tensorflow.python.platform.tf_logging.error", "tensorflow.python.platform.gfile.Stat", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.summary.impl.io_wrapper.IsGCSPath", "tensorflow.python.summary.impl.io_wrapper.ListDirectoryAbsolute", "tensorflow.python.platform.gfile.Exists" ], [ "tensorflow.Variable", "tensorflow.test.main", "tensorflow.python.util.compat.as_bytes", "tensorflow.contrib.learn.Experiment", "tensorflow.ConfigProto", "tensorflow.test.mock.patch", "tensorflow.logging.info", "tensorflow.contrib.learn.python.learn.run_config.RunConfig", "tensorflow.Session", "tensorflow.contrib.learn.python.learn.utils.saved_model_export_utils.make_export_strategy", "tensorflow.train.Saver", "tensorflow.contrib.learn.RunConfig", "tensorflow.test.mock.call", "tensorflow.python.util.all_util.reveal_undocumented" ], [ "tensorflow.python.pywrap_tensorflow.TF_Message", "tensorflow.python.pywrap_tensorflow.TF_DeleteStatus", "tensorflow.python.pywrap_tensorflow.TF_NewStatus", "tensorflow.python.pywrap_tensorflow.TF_GetCode" ], [ "numpy.hstack", "tensorflow.Graph", "tensorflow.python.ops.data_flow_ops.Barrier", "tensorflow.test.main", "numpy.array", "numpy.vstack" ], [ "tensorflow.python.ops.state_ops.assign_sub", "tensorflow.python.framework.ops.add_to_collection", "tensorflow.python.ops.variables.trainable_variables", "tensorflow.python.training.slot_creator.create_zeros_slot", "tensorflow.python.ops.init_ops.ones_initializer", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.math_ops.minimum", "tensorflow.python.ops.variables.global_variables", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.ops.math_ops.truediv", "tensorflow.python.ops.math_ops.div", "tensorflow.python.ops.variables.moving_average_variables", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.ops.variable_scope.get_variable", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.framework.ops.name_scope" ], [ "tensorflow.constant", "tensorflow.gfile.DeleteRecursively", "tensorflow.gfile.Exists", "tensorflow.core.util.test_log_pb2.BenchmarkEntry", "tensorflow.gfile.GFile", "tensorflow.test.main", "tensorflow.gfile.MakeDirs", "tensorflow.Session", "tensorflow.core.util.test_log_pb2.BenchmarkEntries.FromString", "tensorflow.python.platform.benchmark._run_benchmarks", "tensorflow.test.get_temp_dir" ], [ "pandas.Series", "tensorflow.nn.max_pool", "pandas.DataFrame", "tensorflow.contrib.layers.convolution2d", "tensorflow.argmax", "tensorflow.app.run", "tensorflow.one_hot", "tensorflow.contrib.learn.preprocessing.ByteProcessor", "tensorflow.contrib.learn.datasets.load_dataset", "tensorflow.contrib.losses.softmax_cross_entropy", "tensorflow.nn.relu", "tensorflow.reduce_max", "tensorflow.transpose", "tensorflow.nn.softmax", "tensorflow.contrib.framework.get_global_step", "tensorflow.contrib.layers.fully_connected", "tensorflow.contrib.learn.Estimator", "tensorflow.variable_scope", "sklearn.metrics.accuracy_score" ], [ "tensorflow.python.debug.debug_utils.watch_graph_with_blacklists", "tensorflow.core.protobuf.config_pb2.RunOptions", "tensorflow.python.debug.debug_utils.watch_graph", "tensorflow.python.ops.variables.Variable", "tensorflow.python.client.session.Session", "tensorflow.python.ops.math_ops.add", "tensorflow.python.platform.googletest.main", "tensorflow.python.debug.debug_utils.add_debug_tensor_watch", "tensorflow.python.ops.math_ops.matmul", "numpy.array", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.contrib.losses.python.losses.loss_ops.softmax_cross_entropy", "tensorflow.python.ops.nn.softmax", "tensorflow.contrib.losses.python.losses.loss_ops.mean_squared_error", "tensorflow.python.ops.nn.xw_plus_b", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.math_ops.mul", "tensorflow.contrib.framework.deprecated" ], [ "tensorflow.test.main" ], [ "tensorflow.convert_to_tensor", "tensorflow.device", "numpy.asarray", "tensorflow.stack", "tensorflow.SparseTensorValue", "numpy.random.randint", "numpy.testing.assert_equal", "tensorflow.Graph", "tensorflow.Variable", "numpy.arange", "tensorflow.test.main", "tensorflow.deserialize_many_sparse", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.array", "numpy.random.seed", "tensorflow.SparseTensor", "tensorflow.serialize_many_sparse" ], [ "tensorflow.contrib.factorization.kmeans_plus_plus_initialization", "numpy.random.seed", "tensorflow.contrib.factorization.nearest_neighbors", "numpy.random.standard_normal", "tensorflow.test.main", "numpy.tile", "numpy.linalg.norm", "numpy.array" ], [ "tensorflow.device", "tensorflow.python.ops.random_ops.truncated_normal", "numpy.random.seed", "numpy.power", "numpy.isnan", "tensorflow.OptimizerOptions", "tensorflow.test.main", "tensorflow.python.ops.random_ops.parameterized_truncated_normal", "tensorflow.GraphOptions", "tensorflow.Session", "tensorflow.set_random_seed", "numpy.double" ], [ "tensorflow.test.compute_gradient_error", "tensorflow.constant", "numpy.random.seed", "tensorflow.complex_abs", "tensorflow.segment_min", "tensorflow.test.main", "numpy.sign", "numpy.random.randn", "tensorflow.concat_v2", "tensorflow.segment_max", "tensorflow.squared_difference", "tensorflow.abs" ], [ "tensorflow.python.platform.tf_logging.error" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "0.12", "1.0" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "0.12", "1.0" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.13", "1.7", "0.12" ] }, { "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" ] }, { "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" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "0.12", "1.7" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "2.8", "1.2", "2.10" ] } ]
ReyhaneAskari/SLA_violation_classification
[ "258a3c415cebcd04601e4d794d42d664471df668", "258a3c415cebcd04601e4d794d42d664471df668" ]
[ "3_create_database/scripts/createDB2.py", "4_simple_models/scripts/random_forest_SMOTE_bordeline_1.py" ]
[ "# -*- coding: utf-8 -*-\n\n# In this script we find all the history behind an evicted task that has not been finished/killed/failed/lost.\n# We find how many times it has been submitted and what were the events related to this task. \n# The violatedtasks dictionary is the one that is we are looking for. It has only one entry\n# for each (jobid, taskindex) and the rest is stored in a multidimensional array.\n# This database is a test as it is only using 1/500 of the task_events table. \n# Also the not_finished_evictedtasks is only for the first(1/500) part of the tasks_events table.\n# Since the script assumed that the machine state changes in the machine table when a task is added, \n# it is not getting the right results. The problem is that the machines table is only updated when a\n# machine is added so it is just the events of the machines, in order to find the available cpu, \n# memory and disk of a specific machine at the time that a task is assigned to a machine, \n# we need to have more complicated calculations.(refer to createDB3) \n\n# @author: reyhane_askari\n# Universite de Montreal, Dec 2015\n\nfrom os import chdir, listdir\nfrom pandas import read_csv\nfrom os import path\nfrom random import randint, sample, seed\nfrom collections import OrderedDict\nfrom pandas import DataFrame\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport csv\nimport codecs\n\nchdir('/home/askrey/Dropbox/Project_step_by_step/2_find_violations/csvs')\ntask_events_csv_colnames = ['time', 'missing', 'job_id', 'task_idx', 'machine_id', 'event_type', 'user', 'sched_cls', \n 'priority', 'cpu_requested', 'mem_requested', 'disk', 'restriction'] \nevictedtasks = OrderedDict([])\nviolatedtasks = OrderedDict([])\nfor key, val in csv.reader(open(\"not_finished_evictedtasks.csv\")):\n evictedtasks[key] = val\n\nmachines_dictionary = OrderedDict([])\n\n#load machine events table:\nchdir('/home/askrey/Final_project') \nreader = csv.reader(codecs.open('part-00000-of-00001.csv','rU','utf-8'))\n\n# key of machines_dictionary is the primary fields of the machine events table (time, machine id) \n# other fields: event type, platform id, CUPs, memory\n\nfor row in reader:\n machines_dictionary[(row[0],row[1])] = row[2:]\n\n#for fn in sorted(listdir('task_events')):\nfp = path.join('task_events',sorted(listdir('task_events'))[0])\ntask_events_df = read_csv(fp, header = None, index_col = False, names = task_events_csv_colnames, compression = 'gzip')\n\nfor index, event in task_events_df.iterrows():\n \n if (event['job_id'], event['task_idx']) in violatedtasks:\n violatedtasks[event['job_id'],event['task_idx']][0].append(event['time'])\n violatedtasks[event['job_id'],event['task_idx']][2].append(event['machine_id'])\n violatedtasks[event['job_id'],event['task_idx']][3].append(event['event_type'])\n violatedtasks[event['job_id'],event['task_idx']][11].append((machines_dictionary[(str(event['time']),str(event['machine_id']))] if (str(event['time']), str(event['machine_id'])) in machines_dictionary else 0))\n\n elif (\"(\"+str(event['job_id'])+ \", \"+ str(event['task_idx'])+\")\") in evictedtasks:\n violatedtasks[event['job_id'],event['task_idx']] = [[event['time']],event['missing'],[event['machine_id']],\n\t\t\t\t\t\t\t [event['event_type']], event['user'], event['sched_cls'], event['priority'], event['cpu_requested'],\n\t\t\t\t\t\t\t event['mem_requested'], event['disk'], event['restriction'], \n\t\t\t\t\t\t\t [(machines_dictionary[(str(event['time']),str(event['machine_id']))] if (str(event['time']), str(event['machine_id'])) in machines_dictionary else 0 )]]\n\n# moshkel alan in hast k ye jahaE event ha hanooz machine barashoon assign nashode vase hamin hast k machine id nan hast\n\nwriter = csv.writer(open('/home/askrey/Dropbox/Databases/testDB5.csv', 'wb'))\nfor key, value in violatedtasks.items():\n writer.writerow([key, value])\n", "# -*- coding: utf-8 -*-\n\n# In this script we use a simple classifer called naive bayes and try to predict the violations. But before that we use\n# some methods to tackle the problem of our skewed dataset. :) \n\n# 11 May 2016\n# @author: reyhane_askari\n# Universite de Montreal, DIRO\n\nimport csv\nimport numpy as np\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn import metrics\nimport pandas as pd\nfrom os import chdir, listdir\nfrom pandas import read_csv\nfrom os import path\nfrom random import randint, sample, seed\nfrom collections import OrderedDict\nfrom pandas import DataFrame, Series\nimport numpy as np \nimport csv\nimport codecs\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns\nsns.set()\nimport itertools\nfrom sklearn.decomposition import PCA\nfrom unbalanced_dataset import UnderSampler, NearMiss, CondensedNearestNeighbour, OneSidedSelection,\\\nNeighbourhoodCleaningRule, TomekLinks, ClusterCentroids, OverSampler, SMOTE,\\\nSMOTETomek, SMOTEENN, EasyEnsemble, BalanceCascade\n\nalmost_black = '#262626'\n\ncolnames = ['old_index','job_id', 'task_idx','sched_cls', 'priority', 'cpu_requested',\n 'mem_requested', 'disk', 'violation'] \n\ntain_path = r'/home/askrey/Dropbox/Project_step_by_step/3_create_database/csvs/frull_db_2.csv'\n\nX = pd.read_csv(tain_path, header = None, index_col = False ,names = colnames, skiprows = [0], usecols = [3,4,5,6,7])\ny = pd.read_csv(tain_path, header = None, index_col = False ,names = colnames, skiprows = [0], usecols = [8])\ny = y['violation'].values\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.333, random_state=0)\nmain_x = X.values\nmain_y = y\n\nverbose = False\nratio = float(np.count_nonzero(y==1)) / float(np.count_nonzero(y==0))\n# 'SMOTE bordeline 1'\nbsmote1 = SMOTE(ratio=ratio, verbose=verbose, kind='borderline1')\nx, y = bsmote1.fit_transform(main_x, main_y)\n\nratio = float(np.count_nonzero(y==1)) / float(np.count_nonzero(y==0))\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=.333, random_state=0)\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cross_validation import cross_val_score\n\nclf = RandomForestClassifier(n_estimators=10)\nscores = cross_val_score(clf, X_test, y_test)\n\ny_pred = clf.fit(X_train, y_train).predict(X_test)\ny_score = clf.fit(X_train, y_train).predict_proba(X_test)[:,1]\n\n\nmean_accuracy = clf.fit(X_train, y_train).score(X_test,y_test,sample_weight=None)\nfpr, tpr, thresholds = metrics.roc_curve(y_test, y_score)\n\nroc_auc = auc(fpr, tpr)\n\nplt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], 'k--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\n\nplt.savefig('/home/askrey/Dropbox/Project_step_by_step/5_simple_models/new_scripts/random_forest_SMOTE_bordeline_1.pdf')\n" ]
[ [ "pandas.read_csv" ], [ "sklearn.cross_validation.cross_val_score", "matplotlib.pyplot.legend", "sklearn.cross_validation.train_test_split", "pandas.read_csv", "sklearn.ensemble.RandomForestClassifier", "matplotlib.pyplot.title", "matplotlib.use", "matplotlib.pyplot.ylim", "sklearn.metrics.roc_curve", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlim", "matplotlib.pyplot.xlabel", "numpy.count_nonzero", "sklearn.metrics.auc", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
dg4271/haystack
[ "e930d8a717dfca0c7d502f331d7076b51b5f6898", "e930d8a717dfca0c7d502f331d7076b51b5f6898" ]
[ "test/benchmarks/retriever.py", "test/test_retriever.py" ]
[ "import pandas as pd\nfrom pathlib import Path\nfrom time import perf_counter\nfrom utils import get_document_store, get_retriever, index_to_doc_store, load_config\nfrom haystack.preprocessor.utils import eval_data_from_json\nfrom haystack.document_store.faiss import FAISSDocumentStore\n\nfrom haystack import Document\nimport pickle\nimport time\nfrom tqdm import tqdm\nimport logging\nimport datetime\nimport random\nimport traceback\nimport os\nimport requests\nfrom farm.file_utils import download_from_s3\nimport json\nfrom results_to_json import retriever as retriever_json\nfrom templates import RETRIEVER_TEMPLATE, RETRIEVER_MAP_TEMPLATE, RETRIEVER_SPEED_TEMPLATE\n\nlogger = logging.getLogger(__name__)\nlogging.getLogger(\"haystack.retriever.base\").setLevel(logging.WARN)\nlogging.getLogger(\"elasticsearch\").setLevel(logging.WARN)\n\ndoc_index = \"eval_document\"\nlabel_index = \"label\"\n\nindex_results_file = \"retriever_index_results.csv\"\nquery_results_file = \"retriever_query_results.csv\"\n\noverview_json = \"../../docs/_src/benchmarks/retriever_performance.json\"\nmap_json = \"../../docs/_src/benchmarks/retriever_map.json\"\nspeed_json = \"../../docs/_src/benchmarks/retriever_speed.json\"\n\n\nseed = 42\nrandom.seed(42)\n\ndef benchmark_indexing(n_docs_options, retriever_doc_stores, data_dir, filename_gold, filename_negative, data_s3_url, embeddings_filenames, embeddings_dir, update_json, save_markdown, **kwargs):\n\n retriever_results = []\n for n_docs in n_docs_options:\n for retriever_name, doc_store_name in retriever_doc_stores:\n logger.info(f\"##### Start indexing run: {retriever_name}, {doc_store_name}, {n_docs} docs ##### \")\n try:\n doc_store = get_document_store(doc_store_name)\n retriever = get_retriever(retriever_name, doc_store)\n docs, _ = prepare_data(data_dir=data_dir,\n filename_gold=filename_gold,\n filename_negative=filename_negative,\n data_s3_url=data_s3_url,\n embeddings_filenames=embeddings_filenames,\n embeddings_dir=embeddings_dir,\n n_docs=n_docs)\n\n tic = perf_counter()\n index_to_doc_store(doc_store, docs, retriever)\n toc = perf_counter()\n indexing_time = toc - tic\n\n print(indexing_time)\n\n retriever_results.append({\n \"retriever\": retriever_name,\n \"doc_store\": doc_store_name,\n \"n_docs\": n_docs,\n \"indexing_time\": indexing_time,\n \"docs_per_second\": n_docs / indexing_time,\n \"date_time\": datetime.datetime.now(),\n \"error\": None})\n retriever_df = pd.DataFrame.from_records(retriever_results)\n retriever_df = retriever_df.sort_values(by=\"retriever\").sort_values(by=\"doc_store\")\n retriever_df.to_csv(index_results_file)\n logger.info(\"Deleting all docs from this run ...\")\n\n if isinstance(doc_store, FAISSDocumentStore):\n doc_store.session.close()\n else:\n doc_store.delete_all_documents(index=doc_index)\n doc_store.delete_all_documents(index=label_index)\n\n if save_markdown:\n md_file = index_results_file.replace(\".csv\", \".md\")\n with open(md_file, \"w\") as f:\n f.write(str(retriever_df.to_markdown()))\n time.sleep(10)\n del doc_store\n del retriever\n\n except Exception:\n tb = traceback.format_exc()\n logging.error(f\"##### The following Error was raised while running indexing run: {retriever_name}, {doc_store_name}, {n_docs} docs #####\")\n logging.error(tb)\n retriever_results.append({\n \"retriever\": retriever_name,\n \"doc_store\": doc_store_name,\n \"n_docs\": n_docs,\n \"indexing_time\": 0,\n \"docs_per_second\": 0,\n \"date_time\": datetime.datetime.now(),\n \"error\": str(tb)})\n logger.info(\"Deleting all docs from this run ...\")\n if isinstance(doc_store, FAISSDocumentStore):\n doc_store.session.close()\n else:\n doc_store.delete_all_documents(index=doc_index)\n doc_store.delete_all_documents(index=label_index)\n time.sleep(10)\n del doc_store\n del retriever\n if update_json:\n populate_retriever_json()\n\n\n\ndef benchmark_querying(n_docs_options,\n retriever_doc_stores,\n data_dir,\n data_s3_url,\n filename_gold,\n filename_negative,\n n_queries,\n embeddings_filenames,\n embeddings_dir,\n update_json,\n save_markdown,\n **kwargs):\n \"\"\" Benchmark the time it takes to perform querying. Doc embeddings are loaded from file.\"\"\"\n retriever_results = []\n\n for n_docs in n_docs_options:\n for retriever_name, doc_store_name in retriever_doc_stores:\n try:\n logger.info(f\"##### Start querying run: {retriever_name}, {doc_store_name}, {n_docs} docs ##### \")\n if retriever_name == \"elastic\":\n similarity = \"cosine\"\n else:\n similarity = \"dot_product\"\n doc_store = get_document_store(doc_store_name, similarity=similarity)\n retriever = get_retriever(retriever_name, doc_store)\n add_precomputed = retriever_name in [\"dpr\"]\n # For DPR, precomputed embeddings are loaded from file\n docs, labels = prepare_data(data_dir=data_dir,\n filename_gold=filename_gold,\n filename_negative=filename_negative,\n data_s3_url=data_s3_url,\n embeddings_filenames=embeddings_filenames,\n embeddings_dir=embeddings_dir,\n n_docs=n_docs,\n n_queries=n_queries,\n add_precomputed=add_precomputed)\n logger.info(\"Start indexing...\")\n index_to_doc_store(doc_store, docs, retriever, labels)\n logger.info(\"Start queries...\")\n\n raw_results = retriever.eval()\n results = {\n \"retriever\": retriever_name,\n \"doc_store\": doc_store_name,\n \"n_docs\": n_docs,\n \"n_queries\": raw_results[\"n_questions\"],\n \"retrieve_time\": raw_results[\"retrieve_time\"],\n \"queries_per_second\": raw_results[\"n_questions\"] / raw_results[\"retrieve_time\"],\n \"seconds_per_query\": raw_results[\"retrieve_time\"]/ raw_results[\"n_questions\"],\n \"recall\": raw_results[\"recall\"] * 100,\n \"map\": raw_results[\"map\"] * 100,\n \"top_k\": raw_results[\"top_k\"],\n \"date_time\": datetime.datetime.now(),\n \"error\": None\n }\n\n logger.info(\"Deleting all docs from this run ...\")\n if isinstance(doc_store, FAISSDocumentStore):\n doc_store.session.close()\n else:\n doc_store.delete_all_documents(index=doc_index)\n doc_store.delete_all_documents(index=label_index)\n time.sleep(5)\n del doc_store\n del retriever\n except Exception:\n tb = traceback.format_exc()\n logging.error(f\"##### The following Error was raised while running querying run: {retriever_name}, {doc_store_name}, {n_docs} docs #####\")\n logging.error(tb)\n results = {\n \"retriever\": retriever_name,\n \"doc_store\": doc_store_name,\n \"n_docs\": n_docs,\n \"n_queries\": 0,\n \"retrieve_time\": 0.,\n \"queries_per_second\": 0.,\n \"seconds_per_query\": 0.,\n \"recall\": 0.,\n \"map\": 0.,\n \"top_k\": 0,\n \"date_time\": datetime.datetime.now(),\n \"error\": str(tb)\n }\n logger.info(\"Deleting all docs from this run ...\")\n if isinstance(doc_store, FAISSDocumentStore):\n doc_store.session.close()\n else:\n doc_store.delete_all_documents(index=doc_index)\n doc_store.delete_all_documents(index=label_index)\n time.sleep(5)\n del doc_store\n del retriever\n logger.info(results)\n retriever_results.append(results)\n\n retriever_df = pd.DataFrame.from_records(retriever_results)\n retriever_df = retriever_df.sort_values(by=\"retriever\").sort_values(by=\"doc_store\")\n retriever_df.to_csv(query_results_file)\n if save_markdown:\n md_file = query_results_file.replace(\".csv\", \".md\")\n with open(md_file, \"w\") as f:\n f.write(str(retriever_df.to_markdown()))\n if update_json:\n populate_retriever_json()\n\n\ndef populate_retriever_json():\n retriever_overview_data, retriever_map_data, retriever_speed_data = retriever_json(index_csv=index_results_file,\n query_csv=query_results_file)\n overview = RETRIEVER_TEMPLATE\n overview[\"data\"] = retriever_overview_data\n map = RETRIEVER_MAP_TEMPLATE\n map[\"data\"] = retriever_map_data\n speed = RETRIEVER_SPEED_TEMPLATE\n speed[\"data\"] = retriever_speed_data\n json.dump(overview, open(overview_json, \"w\"), indent=4)\n json.dump(speed, open(speed_json, \"w\"), indent=4)\n json.dump(map, open(map_json, \"w\"), indent=4)\n\n\ndef add_precomputed_embeddings(embeddings_dir, embeddings_filenames, docs):\n ret = []\n id_to_doc = {x.meta[\"passage_id\"]: x for x in docs}\n for ef in embeddings_filenames:\n logger.info(f\"Adding precomputed embeddings from {embeddings_dir + ef}\")\n filename = embeddings_dir + ef\n embeds = pickle.load(open(filename, \"rb\"))\n for i, vec in embeds:\n if int(i) in id_to_doc:\n curr = id_to_doc[int(i)]\n curr.embedding = vec\n ret.append(curr)\n # In the official DPR repo, there are only 20594995 precomputed embeddings for 21015324 wikipedia passages\n # If there isn't an embedding for a given doc, we remove it here\n ret = [x for x in ret if x.embedding is not None]\n logger.info(f\"Embeddings loaded for {len(ret)}/{len(docs)} docs\")\n return ret\n\n\ndef prepare_data(data_dir, filename_gold, filename_negative, data_s3_url, embeddings_filenames, embeddings_dir, n_docs=None, n_queries=None, add_precomputed=False):\n \"\"\"\n filename_gold points to a squad format file.\n filename_negative points to a csv file where the first column is doc_id and second is document text.\n If add_precomputed is True, this fn will look in the embeddings files for precomputed embeddings to add to each Document\n \"\"\"\n\n logging.getLogger(\"farm\").setLevel(logging.INFO)\n download_from_s3(data_s3_url + filename_gold, cache_dir=data_dir)\n download_from_s3(data_s3_url + filename_negative, cache_dir=data_dir)\n if add_precomputed:\n for embedding_filename in embeddings_filenames:\n download_from_s3(data_s3_url + str(embeddings_dir) + embedding_filename, cache_dir=data_dir)\n logging.getLogger(\"farm\").setLevel(logging.WARN)\n\n gold_docs, labels = eval_data_from_json(data_dir + filename_gold)\n\n # Reduce number of docs\n gold_docs = gold_docs[:n_docs]\n\n # Remove labels whose gold docs have been removed\n doc_ids = [x.id for x in gold_docs]\n labels = [x for x in labels if x.document_id in doc_ids]\n\n # Filter labels down to n_queries\n selected_queries = list(set(f\"{x.document_id} | {x.question}\" for x in labels))\n selected_queries = selected_queries[:n_queries]\n labels = [x for x in labels if f\"{x.document_id} | {x.question}\" in selected_queries]\n\n n_neg_docs = max(0, n_docs - len(gold_docs))\n neg_docs = prepare_negative_passages(data_dir, filename_negative, n_neg_docs)\n docs = gold_docs + neg_docs\n\n if add_precomputed:\n docs = add_precomputed_embeddings(data_dir + embeddings_dir, embeddings_filenames, docs)\n\n return docs, labels\n\ndef prepare_negative_passages(data_dir, filename_negative, n_docs):\n if n_docs == 0:\n return []\n with open(data_dir + filename_negative) as f:\n lines = []\n _ = f.readline() # Skip column titles line\n for _ in range(n_docs):\n lines.append(f.readline()[:-1])\n\n docs = []\n for l in lines[:n_docs]:\n id, text, title = l.split(\"\\t\")\n d = {\"text\": text,\n \"meta\": {\"passage_id\": int(id),\n \"title\": title}}\n d = Document(**d)\n docs.append(d)\n return docs\n\n\nif __name__ == \"__main__\":\n params, filenames = load_config(config_filename=\"config.json\", ci=True)\n benchmark_indexing(**params, **filenames, update_json=True, save_markdown=False)\n benchmark_querying(**params, **filenames, update_json=True, save_markdown=False)\n\n", "import time\n\nimport numpy as np\nimport pytest\nfrom elasticsearch import Elasticsearch\nfrom haystack import Document\nfrom haystack.document_store.elasticsearch import ElasticsearchDocumentStore\nfrom haystack.document_store.faiss import FAISSDocumentStore\nfrom haystack.document_store.milvus import MilvusDocumentStore\nfrom haystack.retriever.dense import DensePassageRetriever\nfrom haystack.retriever.sparse import ElasticsearchRetriever, ElasticsearchFilterOnlyRetriever, TfidfRetriever\nfrom transformers import DPRContextEncoderTokenizerFast, DPRQuestionEncoderTokenizerFast\n\n\[email protected]\[email protected](\n \"retriever_with_docs,document_store_with_docs\",\n [\n (\"dpr\", \"elasticsearch\"),\n (\"dpr\", \"faiss\"),\n (\"dpr\", \"memory\"),\n (\"dpr\", \"milvus\"),\n (\"embedding\", \"elasticsearch\"),\n (\"embedding\", \"faiss\"),\n (\"embedding\", \"memory\"),\n (\"embedding\", \"milvus\"),\n (\"elasticsearch\", \"elasticsearch\"),\n (\"es_filter_only\", \"elasticsearch\"),\n (\"tfidf\", \"memory\"),\n ],\n indirect=True,\n)\ndef test_retrieval(retriever_with_docs, document_store_with_docs):\n if not isinstance(retriever_with_docs, (ElasticsearchRetriever, ElasticsearchFilterOnlyRetriever, TfidfRetriever)):\n document_store_with_docs.update_embeddings(retriever_with_docs)\n\n # test without filters\n res = retriever_with_docs.retrieve(query=\"Who lives in Berlin?\")\n assert res[0].text == \"My name is Carla and I live in Berlin\"\n assert len(res) == 3\n assert res[0].meta[\"name\"] == \"filename1\"\n\n # test with filters\n if not isinstance(document_store_with_docs, (FAISSDocumentStore, MilvusDocumentStore)) and not isinstance(\n retriever_with_docs, TfidfRetriever\n ):\n # single filter\n result = retriever_with_docs.retrieve(query=\"godzilla\", filters={\"name\": [\"filename3\"]}, top_k=5)\n assert len(result) == 1\n assert type(result[0]) == Document\n assert result[0].text == \"My name is Christelle and I live in Paris\"\n assert result[0].meta[\"name\"] == \"filename3\"\n\n # multiple filters\n result = retriever_with_docs.retrieve(\n query=\"godzilla\", filters={\"name\": [\"filename2\"], \"meta_field\": [\"test2\", \"test3\"]}, top_k=5\n )\n assert len(result) == 1\n assert type(result[0]) == Document\n assert result[0].meta[\"name\"] == \"filename2\"\n\n result = retriever_with_docs.retrieve(\n query=\"godzilla\", filters={\"name\": [\"filename1\"], \"meta_field\": [\"test2\", \"test3\"]}, top_k=5\n )\n assert len(result) == 0\n\n\[email protected]\ndef test_elasticsearch_custom_query(elasticsearch_fixture):\n client = Elasticsearch()\n client.indices.delete(index=\"haystack_test_custom\", ignore=[404])\n document_store = ElasticsearchDocumentStore(\n index=\"haystack_test_custom\", text_field=\"custom_text_field\", embedding_field=\"custom_embedding_field\"\n )\n documents = [\n {\"text\": \"test_1\", \"meta\": {\"year\": \"2019\"}},\n {\"text\": \"test_2\", \"meta\": {\"year\": \"2020\"}},\n {\"text\": \"test_3\", \"meta\": {\"year\": \"2021\"}},\n {\"text\": \"test_4\", \"meta\": {\"year\": \"2021\"}},\n {\"text\": \"test_5\", \"meta\": {\"year\": \"2021\"}},\n ]\n document_store.write_documents(documents)\n\n # test custom \"terms\" query\n retriever = ElasticsearchRetriever(\n document_store=document_store,\n custom_query=\"\"\"\n {\n \"size\": 10, \n \"query\": {\n \"bool\": {\n \"should\": [{\n \"multi_match\": {\"query\": ${query}, \"type\": \"most_fields\", \"fields\": [\"text\"]}}],\n \"filter\": [{\"terms\": {\"year\": ${years}}}]}}}\"\"\",\n )\n results = retriever.retrieve(query=\"test\", filters={\"years\": [\"2020\", \"2021\"]})\n assert len(results) == 4\n\n # test custom \"term\" query\n retriever = ElasticsearchRetriever(\n document_store=document_store,\n custom_query=\"\"\"\n {\n \"size\": 10, \n \"query\": {\n \"bool\": {\n \"should\": [{\n \"multi_match\": {\"query\": ${query}, \"type\": \"most_fields\", \"fields\": [\"text\"]}}],\n \"filter\": [{\"term\": {\"year\": ${years}}}]}}}\"\"\",\n )\n results = retriever.retrieve(query=\"test\", filters={\"years\": \"2021\"})\n assert len(results) == 3\n\n\[email protected]\[email protected]\[email protected](\"document_store\", [\"elasticsearch\", \"faiss\", \"memory\", \"milvus\"], indirect=True)\[email protected](\"retriever\", [\"dpr\"], indirect=True)\ndef test_dpr_embedding(document_store, retriever):\n documents = [\n Document(\n text=\"\"\"Aaron Aaron ( or ; \"\"Ahärôn\"\") is a prophet, high priest, and the brother of Moses in the Abrahamic religions. Knowledge of Aaron, along with his brother Moses, comes exclusively from religious texts, such as the Bible and Quran. The Hebrew Bible relates that, unlike Moses, who grew up in the Egyptian royal court, Aaron and his elder sister Miriam remained with their kinsmen in the eastern border-land of Egypt (Goshen). When Moses first confronted the Egyptian king about the Israelites, Aaron served as his brother's spokesman (\"\"prophet\"\") to the Pharaoh. Part of the Law (Torah) that Moses received from\"\"\",\n meta={\"name\": \"0\"},\n id=\"1\",\n ),\n Document(\n text=\"\"\"Democratic Republic of the Congo to the south. Angola's capital, Luanda, lies on the Atlantic coast in the northwest of the country. Angola, although located in a tropical zone, has a climate that is not characterized for this region, due to the confluence of three factors: As a result, Angola's climate is characterized by two seasons: rainfall from October to April and drought, known as \"\"Cacimbo\"\", from May to August, drier, as the name implies, and with lower temperatures. On the other hand, while the coastline has high rainfall rates, decreasing from North to South and from to , with\"\"\",\n id=\"2\",\n ),\n Document(\n text=\"\"\"Schopenhauer, describing him as an ultimately shallow thinker: \"\"Schopenhauer has quite a crude mind ... where real depth starts, his comes to an end.\"\" His friend Bertrand Russell had a low opinion on the philosopher, and attacked him in his famous \"\"History of Western Philosophy\"\" for hypocritically praising asceticism yet not acting upon it. On the opposite isle of Russell on the foundations of mathematics, the Dutch mathematician L. E. J. Brouwer incorporated the ideas of Kant and Schopenhauer in intuitionism, where mathematics is considered a purely mental activity, instead of an analytic activity wherein objective properties of reality are\"\"\",\n meta={\"name\": \"1\"},\n id=\"3\",\n ),\n Document(\n text=\"\"\"The Dothraki vocabulary was created by David J. Peterson well in advance of the adaptation. HBO hired the Language Creatio\"\"\",\n meta={\"name\": \"2\"},\n id=\"4\",\n ),\n Document(\n text=\"\"\"The title of the episode refers to the Great Sept of Baelor, the main religious building in King's Landing, where the episode's pivotal scene takes place. In the world created by George R. R. Martin\"\"\",\n meta={},\n id=\"5\",\n ),\n ]\n\n document_store.return_embedding = True\n document_store.write_documents(documents)\n document_store.update_embeddings(retriever=retriever)\n time.sleep(1)\n\n doc_1 = document_store.get_document_by_id(\"1\")\n assert len(doc_1.embedding) == 768\n assert abs(doc_1.embedding[0] - (-0.3063)) < 0.001\n doc_2 = document_store.get_document_by_id(\"2\")\n assert abs(doc_2.embedding[0] - (-0.3914)) < 0.001\n doc_3 = document_store.get_document_by_id(\"3\")\n assert abs(doc_3.embedding[0] - (-0.2470)) < 0.001\n doc_4 = document_store.get_document_by_id(\"4\")\n assert abs(doc_4.embedding[0] - (-0.0802)) < 0.001\n doc_5 = document_store.get_document_by_id(\"5\")\n assert abs(doc_5.embedding[0] - (-0.0551)) < 0.001\n\n\[email protected](\"retriever\", [\"dpr\"], indirect=True)\[email protected](\"document_store\", [\"memory\"], indirect=True)\ndef test_dpr_saving_and_loading(retriever, document_store):\n retriever.save(\"test_dpr_save\")\n\n def sum_params(model):\n s = []\n for p in model.parameters():\n n = p.cpu().data.numpy()\n s.append(np.sum(n))\n return sum(s)\n\n original_sum_query = sum_params(retriever.query_encoder)\n original_sum_passage = sum_params(retriever.passage_encoder)\n del retriever\n\n loaded_retriever = DensePassageRetriever.load(\"test_dpr_save\", document_store)\n\n loaded_sum_query = sum_params(loaded_retriever.query_encoder)\n loaded_sum_passage = sum_params(loaded_retriever.passage_encoder)\n\n assert abs(original_sum_query - loaded_sum_query) < 0.1\n assert abs(original_sum_passage - loaded_sum_passage) < 0.1\n\n # comparison of weights (RAM intense!)\n # for p1, p2 in zip(retriever.query_encoder.parameters(), loaded_retriever.query_encoder.parameters()):\n # assert (p1.data.ne(p2.data).sum() == 0)\n #\n # for p1, p2 in zip(retriever.passage_encoder.parameters(), loaded_retriever.passage_encoder.parameters()):\n # assert (p1.data.ne(p2.data).sum() == 0)\n\n # attributes\n assert loaded_retriever.embed_title == True\n assert loaded_retriever.batch_size == 16\n assert loaded_retriever.max_seq_len_passage == 256\n assert loaded_retriever.max_seq_len_query == 64\n\n # Tokenizer\n assert isinstance(loaded_retriever.passage_tokenizer, DPRContextEncoderTokenizerFast)\n assert isinstance(loaded_retriever.query_tokenizer, DPRQuestionEncoderTokenizerFast)\n assert loaded_retriever.passage_tokenizer.do_lower_case == True\n assert loaded_retriever.query_tokenizer.do_lower_case == True\n assert loaded_retriever.passage_tokenizer.vocab_size == 30522\n assert loaded_retriever.query_tokenizer.vocab_size == 30522\n assert loaded_retriever.passage_tokenizer.model_max_length == 512\n assert loaded_retriever.query_tokenizer.model_max_length == 512\n" ]
[ [ "pandas.DataFrame.from_records" ], [ "numpy.sum" ] ]
[ { "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": [], "tensorflow": [] } ]
khawar512/OPVT
[ "690e540e7f54e43751d28a046009993e3e325291", "690e540e7f54e43751d28a046009993e3e325291" ]
[ "vit_pytorch/do_conv_pytorch.py", "vit_pytorch/efficient_VIT.py" ]
[ "# coding=utf-8\n\nimport math\nimport torch\nimport numpy as np\nfrom torch.nn import init\nfrom itertools import repeat\nfrom torch.nn import functional as F\nimport collections.abc as container_abcs\nfrom typing import Optional\nfrom torch.nn.parameter import Parameter\nfrom torch.nn.modules.module import Module\n\n\nclass DOConv2d(Module):\n \"\"\"\n DOConv2d can be used as an alternative for torch.nn.Conv2d.\n The interface is similar to that of Conv2d, with one exception:\n 1. D_mul: the depth multiplier for the over-parameterization.\n Note that the groups parameter switchs between DO-Conv (groups=1),\n DO-DConv (groups=in_channels), DO-GConv (otherwise).\n \"\"\"\n __constants__ = ['stride', 'padding', 'dilation', 'groups',\n 'padding_mode', 'output_padding', 'in_channels',\n 'out_channels', 'kernel_size', 'D_mul']\n __annotations__ = {'bias': Optional[torch.Tensor]}\n\n def __init__(self, in_channels, out_channels, kernel_size, D_mul=None, stride=1,\n padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros'):\n super(DOConv2d, self).__init__()\n\n kernel_size = _pair(kernel_size)\n stride = _pair(stride)\n padding = _pair(padding)\n dilation = _pair(dilation)\n\n if in_channels % groups != 0:\n raise ValueError('in_channels must be divisible by groups')\n if out_channels % groups != 0:\n raise ValueError('out_channels must be divisible by groups')\n valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'}\n if padding_mode not in valid_padding_modes:\n raise ValueError(\"padding_mode must be one of {}, but got padding_mode='{}'\".format(\n valid_padding_modes, padding_mode))\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.dilation = dilation\n self.groups = groups\n self.padding_mode = padding_mode\n self._padding_repeated_twice = tuple(x for x in self.padding for _ in range(2))\n\n #################################### Initailization of D & W ###################################\n M = self.kernel_size[0]\n N = self.kernel_size[1]\n self.D_mul = M * N if D_mul is None or M * N <= 1 else D_mul\n self.W = Parameter(torch.Tensor(out_channels, in_channels // groups, self.D_mul))\n init.kaiming_uniform_(self.W, a=math.sqrt(5))\n\n if M * N > 1:\n self.D = Parameter(torch.Tensor(in_channels, M * N, self.D_mul))\n init_zero = np.zeros([in_channels, M * N, self.D_mul], dtype=np.float32)\n self.D.data = torch.from_numpy(init_zero)\n\n eye = torch.reshape(torch.eye(M * N, dtype=torch.float32), (1, M * N, M * N))\n D_diag = eye.repeat((in_channels, 1, self.D_mul // (M * N)))\n if self.D_mul % (M * N) != 0: # the cases when D_mul > M * N\n zeros = torch.zeros([in_channels, M * N, self.D_mul % (M * N)])\n self.D_diag = Parameter(torch.cat([D_diag, zeros], dim=2), requires_grad=False)\n else: # the case when D_mul = M * N\n self.D_diag = Parameter(D_diag, requires_grad=False)\n ##################################################################################################\n\n if bias:\n self.bias = Parameter(torch.Tensor(out_channels))\n fan_in, _ = init._calculate_fan_in_and_fan_out(self.W)\n bound = 1 / math.sqrt(fan_in)\n init.uniform_(self.bias, -bound, bound)\n else:\n self.register_parameter('bias', None)\n\n def extra_repr(self):\n s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'\n ', stride={stride}')\n if self.padding != (0,) * len(self.padding):\n s += ', padding={padding}'\n if self.dilation != (1,) * len(self.dilation):\n s += ', dilation={dilation}'\n if self.groups != 1:\n s += ', groups={groups}'\n if self.bias is None:\n s += ', bias=False'\n if self.padding_mode != 'zeros':\n s += ', padding_mode={padding_mode}'\n return s.format(**self.__dict__)\n\n def __setstate__(self, state):\n super(DOConv2d, self).__setstate__(state)\n if not hasattr(self, 'padding_mode'):\n self.padding_mode = 'zeros'\n\n def _conv_forward(self, input, weight):\n if self.padding_mode != 'zeros':\n return F.conv2d(F.pad(input, self._padding_repeated_twice, mode=self.padding_mode),\n weight, self.bias, self.stride,\n _pair(0), self.dilation, self.groups)\n return F.conv2d(input, weight, self.bias, self.stride,\n self.padding, self.dilation, self.groups)\n\n def forward(self, input):\n M = self.kernel_size[0]\n N = self.kernel_size[1]\n DoW_shape = (self.out_channels, self.in_channels // self.groups, M, N)\n if M * N > 1:\n ######################### Compute DoW #################\n # (input_channels, D_mul, M * N)\n D = self.D + self.D_diag\n W = torch.reshape(self.W, (self.out_channels // self.groups, self.in_channels, self.D_mul))\n\n # einsum outputs (out_channels // groups, in_channels, M * N),\n # which is reshaped to\n # (out_channels, in_channels // groups, M, N)\n DoW = torch.reshape(torch.einsum('ims,ois->oim', D, W), DoW_shape)\n #######################################################\n else:\n # in this case D_mul == M * N\n # reshape from\n # (out_channels, in_channels // groups, D_mul)\n # to\n # (out_channels, in_channels // groups, M, N)\n DoW = torch.reshape(self.W, DoW_shape)\n return self._conv_forward(input, DoW)\n\n\ndef _ntuple(n):\n def parse(x):\n if isinstance(x, container_abcs.Iterable):\n return x\n return tuple(repeat(x, n))\n\n return parse\n\n\n_pair = _ntuple(2)", "import torch\nfrom torch import nn\nfrom einops import rearrange, repeat\nfrom einops.layers.torch import Rearrange\nfrom vit_pytorch.face_losses import CosFace, ArcFace, SFaceLoss, Softmax\n\nMIN_NUM_PATCHES = 16\nclass ViT(nn.Module):\n def __init__(self, *, image_size, loss_type, GPU_ID, pad=4, ac_patch_size, patch_size, num_classes, dim, transformer, pool='cls', channels=3):\n super().__init__()\n assert image_size % patch_size == 0, 'Image dimensions must be divisible by the patch size.'\n num_patches = (image_size // patch_size) ** 2\n patch_dim = channels * ac_patch_size ** 2\n assert num_patches > MIN_NUM_PATCHES, f'your number of patches ({num_patches}) is way too small for attention to be effective (at least 16). Try decreasing your patch size'\n assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)'\n\n self.patch_size = patch_size\n self.soft_split = nn.Unfold(kernel_size=(ac_patch_size, ac_patch_size),\n stride=(self.patch_size, self.patch_size), padding=(pad, pad))\n\n self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))\n self.to_patch_embedding = nn.Linear(patch_dim, dim)\n self.cls_token = nn.Parameter(torch.randn(1, 1, dim))\n self.transformer = transformer\n\n self.pool = pool\n self.to_latent = nn.Identity()\n\n self.mlp_head = nn.Sequential(\n nn.LayerNorm(dim),\n #nn.Linear(dim, num_classes)\n )\n self.loss_type = loss_type\n self.GPU_ID = GPU_ID\n if self.loss_type == 'None':\n print(\"no loss for vit_face\")\n else:\n if self.loss_type == 'Softmax':\n self.loss = Softmax(in_features=dim, out_features=num_classes, device_id=self.GPU_ID)\n elif self.loss_type == 'CosFace':\n self.loss = CosFace(in_features=dim, out_features=num_classes, device_id=self.GPU_ID)\n elif self.loss_type == 'ArcFace':\n self.loss = ArcFace(in_features=dim, out_features=num_classes, device_id=self.GPU_ID)\n elif self.loss_type == 'SFace':\n self.loss = SFaceLoss(in_features=dim, out_features=num_classes, device_id=self.GPU_ID)\n\n def forward(self, img, label=None, mask=None):\n p = self.patch_size\n x = self.soft_split(img).transpose(1, 2)\n x = self.to_patch_embedding(x)\n b, n, _ = x.shape\n\n cls_tokens = repeat(self.cls_token, '() n d -> b n d', b=b)\n x = torch.cat((cls_tokens, x), dim=1)\n x += self.pos_embedding[:, :(n + 1)]\n x = self.transformer(x, mask)\n\n x = x.mean(dim=1) if self.pool == 'mean' else x[:, 0]\n\n x = self.to_latent(x)\n emb = self.mlp_head(x)\n\n if label is not None:\n x = self.loss(emb, label)\n return x, emb\n else:\n return emb\n" ]
[ [ "torch.nn.init.uniform_", "torch.Tensor", "torch.zeros", "torch.cat", "torch.einsum", "torch.nn.functional.conv2d", "torch.reshape", "torch.eye", "torch.from_numpy", "torch.nn.parameter.Parameter", "torch.nn.init._calculate_fan_in_and_fan_out", "numpy.zeros", "torch.nn.functional.pad" ], [ "torch.cat", "torch.randn", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.nn.Unfold", "torch.nn.Identity" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gunpowder78/google-research
[ "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5" ]
[ "unprocessing/process.py", "tf3d/object_detection/preprocessor_test.py", "combiner/combiner/tf/approx_attention.py", "polish/ppo/ppo_model_fn.py", "scann/configure.py", "ebp/ebp/common/plot_utils/plot_2d.py", "aloe/aloe/rfill/seq_embed.py", "neutra/ebm/train_ebm.py", "readtwice/models/optimization.py", "robust_retrieval/evaluate.py", "symbolic_functionals/syfes/symbolic/search_utils.py", "simpdom/seq_tagging_metric_util.py", "value_dice/value_dice.py", "cold_posterior_flax/cifar10/train_test.py", "aqt/jax/wmt_mlperf/train_test.py", "rl_repr/contrastive_fourier/tabular_bc_energy.py", "learning_parameter_allocation/pathnet/components.py", "structformer/structformer.py", "snlds/model_cavi_snlds.py", "kws_streaming/layers/random_stretch_squeeze_test.py", "keypose/utils.py", "latent_programmer/tasks/robust_fill/dataset/input_pipeline.py", "coltran/custom_colorize.py", "bitempered_loss/loss_test.py", "factorize_a_city/relight_scene.py", "ravens/ravens/models/transport.py", "differentiable_data_selection/augment.py", "reset_free_learning/envs/reset_free_wrapper.py", "scrna_benchmark/scvi_process.py", "cnn_quantization/tf_cnn_benchmarks/cnn_util.py" ]
[ "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Forward processing of raw data to sRGB images.\n\nUnprocessing Images for Learned Raw Denoising\nhttp://timothybrooks.com/tech/unprocessing\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v1 as tf\n\n\ndef apply_gains(bayer_images, red_gains, blue_gains):\n \"\"\"Applies white balance gains to a batch of Bayer images.\"\"\"\n bayer_images.shape.assert_is_compatible_with((None, None, None, 4))\n green_gains = tf.ones_like(red_gains)\n gains = tf.stack([red_gains, green_gains, green_gains, blue_gains], axis=-1)\n gains = gains[:, tf.newaxis, tf.newaxis, :]\n return bayer_images * gains\n\n\ndef demosaic(bayer_images):\n \"\"\"Bilinearly demosaics a batch of RGGB Bayer images.\"\"\"\n bayer_images.shape.assert_is_compatible_with((None, None, None, 4))\n\n # This implementation exploits how edges are aligned when upsampling with\n # tf.image.resize_bilinear().\n\n with tf.name_scope(None, 'demosaic'):\n shape = tf.shape(bayer_images)\n shape = [shape[1] * 2, shape[2] * 2]\n\n red = bayer_images[Ellipsis, 0:1]\n red = tf.image.resize_bilinear(red, shape)\n\n green_red = bayer_images[Ellipsis, 1:2]\n green_red = tf.image.flip_left_right(green_red)\n green_red = tf.image.resize_bilinear(green_red, shape)\n green_red = tf.image.flip_left_right(green_red)\n green_red = tf.space_to_depth(green_red, 2)\n\n green_blue = bayer_images[Ellipsis, 2:3]\n green_blue = tf.image.flip_up_down(green_blue)\n green_blue = tf.image.resize_bilinear(green_blue, shape)\n green_blue = tf.image.flip_up_down(green_blue)\n green_blue = tf.space_to_depth(green_blue, 2)\n\n green_at_red = (green_red[Ellipsis, 0] + green_blue[Ellipsis, 0]) / 2\n green_at_green_red = green_red[Ellipsis, 1]\n green_at_green_blue = green_blue[Ellipsis, 2]\n green_at_blue = (green_red[Ellipsis, 3] + green_blue[Ellipsis, 3]) / 2\n\n green_planes = [\n green_at_red, green_at_green_red, green_at_green_blue, green_at_blue\n ]\n green = tf.depth_to_space(tf.stack(green_planes, axis=-1), 2)\n\n blue = bayer_images[Ellipsis, 3:4]\n blue = tf.image.flip_up_down(tf.image.flip_left_right(blue))\n blue = tf.image.resize_bilinear(blue, shape)\n blue = tf.image.flip_up_down(tf.image.flip_left_right(blue))\n\n rgb_images = tf.concat([red, green, blue], axis=-1)\n return rgb_images\n\n\ndef apply_ccms(images, ccms):\n \"\"\"Applies color correction matrices.\"\"\"\n images.shape.assert_has_rank(4)\n images = images[:, :, :, tf.newaxis, :]\n ccms = ccms[:, tf.newaxis, tf.newaxis, :, :]\n return tf.reduce_sum(images * ccms, axis=-1)\n\n\ndef gamma_compression(images, gamma=2.2):\n \"\"\"Converts from linear to gamma space.\"\"\"\n # Clamps to prevent numerical instability of gradients near zero.\n return tf.maximum(images, 1e-8) ** (1.0 / gamma)\n\n\ndef process(bayer_images, red_gains, blue_gains, cam2rgbs):\n \"\"\"Processes a batch of Bayer RGGB images into sRGB images.\"\"\"\n bayer_images.shape.assert_is_compatible_with((None, None, None, 4))\n with tf.name_scope(None, 'process'):\n # White balance.\n bayer_images = apply_gains(bayer_images, red_gains, blue_gains)\n # Demosaic.\n bayer_images = tf.clip_by_value(bayer_images, 0.0, 1.0)\n images = demosaic(bayer_images)\n # Color correction.\n images = apply_ccms(images, cam2rgbs)\n # Gamma compression.\n images = tf.clip_by_value(images, 0.0, 1.0)\n images = gamma_compression(images)\n return images\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for ...object_detection.preprocessor.\"\"\"\n\nimport tensorflow as tf\nfrom tf3d import standard_fields\nfrom tf3d.object_detection import preprocessor\n\n\nclass ObjectDetectionPreprocessorTest(tf.test.TestCase):\n\n def _image_correspondence_fn(self, inputs):\n return {\n 'view_images': {\n 'rgb_view':\n tf.cast(\n tf.zeros([5, 200, 300, 3], dtype=tf.int32), dtype=tf.uint8),\n },\n 'view_indices_2d': {\n 'rgb_view':\n tf.random.uniform([5, 100, 2],\n minval=-10,\n maxval=1000,\n dtype=tf.int32)\n }\n }\n\n def _get_input_dict(self, height=240, width=320):\n return {\n standard_fields.InputDataFields.camera_image:\n tf.zeros((height, width, 3), dtype=tf.uint8),\n standard_fields.InputDataFields.point_positions:\n tf.random.uniform((100, 3), minval=-1, maxval=1),\n standard_fields.InputDataFields.camera_intrinsics:\n tf.constant([\n [160.0, 0.0, 160.0], # fx, s, cx\n [0.0, 160.0, 120.0], # 0, fy, cy\n [0.0, 0.0, 1.0], # 0, 0, 1\n ]),\n standard_fields.InputDataFields.camera_rotation_matrix:\n tf.eye(3),\n standard_fields.InputDataFields.camera_translation:\n tf.constant([0., 0., 2.]),\n standard_fields.InputDataFields.objects_class:\n tf.constant([1, 4, 5]),\n standard_fields.InputDataFields.objects_length:\n tf.constant([[4.0], [1.0], [1.0]]),\n standard_fields.InputDataFields.objects_height:\n tf.constant([[2.0], [1.0], [4.0]]),\n standard_fields.InputDataFields.objects_width:\n tf.constant([[2.0], [1.0], [1.0]]),\n standard_fields.InputDataFields.objects_rotation_matrix:\n tf.constant([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],\n [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],\n [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]]),\n standard_fields.InputDataFields.objects_center:\n tf.constant([[4.0, 4.0, 4.0], [2.5, 2.5, 2.5], [0.5, 1.5, 9.5]]),\n standard_fields.InputDataFields.objects_difficulty:\n tf.constant([[1], [1], [1]]),\n standard_fields.InputDataFields.objects_instance_id:\n tf.constant([[1], [2], [1]]),\n standard_fields.InputDataFields.objects_has_3d_info:\n tf.constant([1, 1, 0]),\n standard_fields.InputDataFields.camera_image_name:\n tf.convert_to_tensor('image', tf.string),\n }\n\n def test_preprocess_output_shapes(self):\n height, width = (240, 320)\n input_dict = self._get_input_dict(height, width)\n object_keys = preprocessor._OBJECT_KEYS\n output_keys = [\n standard_fields.InputDataFields.camera_intrinsics,\n standard_fields.InputDataFields.camera_rotation_matrix,\n standard_fields.InputDataFields.camera_translation,\n standard_fields.InputDataFields.point_positions,\n standard_fields.InputDataFields.num_valid_points,\n standard_fields.InputDataFields.object_class_points,\n standard_fields.InputDataFields.object_center_points,\n standard_fields.InputDataFields.object_height_points,\n standard_fields.InputDataFields.object_width_points,\n standard_fields.InputDataFields.object_rotation_matrix_points,\n standard_fields.InputDataFields.object_length_points,\n standard_fields.InputDataFields.object_instance_id_points,\n ]\n output_dict = preprocessor.preprocess(\n inputs=input_dict,\n images_points_correspondence_fn=self._image_correspondence_fn,\n image_preprocess_fn_dic=None)\n for key in output_keys:\n self.assertIn(key, output_dict)\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.camera_intrinsics].shape,\n (3, 3))\n self.assertEqual(\n output_dict[\n standard_fields.InputDataFields.camera_rotation_matrix].shape,\n (3, 3))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.camera_translation].shape,\n (3,))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.point_positions].shape,\n (100, 3))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.num_valid_points].numpy(),\n 100)\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.object_class_points].shape,\n (100,))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.object_center_points].shape,\n (100, 3))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.object_height_points].shape,\n (100, 1))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.object_width_points].shape,\n (100, 1))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields.object_length_points].shape,\n (100, 1))\n self.assertEqual(\n output_dict[standard_fields.InputDataFields\n .object_rotation_matrix_points].shape, (100, 3, 3))\n self.assertEqual(\n output_dict[\n standard_fields.InputDataFields.object_instance_id_points].shape,\n (100,))\n for key in object_keys:\n self.assertEqual(output_dict[key].shape[0], 2)\n\n def test_preprocess_output_keys(self):\n height, width = (240, 320)\n input_dict = self._get_input_dict(height, width)\n output_dict = preprocessor.preprocess(\n inputs=input_dict,\n images_points_correspondence_fn=self._image_correspondence_fn,\n output_keys=[standard_fields.InputDataFields.camera_image],\n image_preprocess_fn_dic=None)\n self.assertIn(standard_fields.InputDataFields.camera_image, output_dict)\n self.assertEqual(len(output_dict.keys()), 1)\n\n def test_preprocess_missing_input_raises(self):\n with self.assertRaises(ValueError):\n empty_input = {}\n preprocessor.preprocess(inputs=empty_input)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: skip-file\nimport tensorflow.compat.v1 as tf\nimport math\nfrom combiner.tf import attention\nfrom combiner.tf import ops\nimport functools\n\n\ndef shift_right(x, axis):\n \"\"\"Shift input x to the right along given axis.\"\"\"\n pad_widths = [(0, 0)] * len(x.shape)\n pad_widths[axis] = (1, 0)\n padded = tf.pad(x, pad_widths)\n return tf.slice(padded, begin=[0]*len(x.shape), size=x.shape)\n\n\ndef shift_left(x, axis):\n \"\"\"Shift input x to the left along given axis.\"\"\"\n pad_widths = [(0, 0)] * len(x.shape)\n pad_widths[axis] = (0, 1)\n padded = tf.pad(x, pad_widths)\n begin = [0]*len(x.shape)\n begin[axis] = 1\n return tf.slice(padded, begin=begin, size=x.shape)\n\n\ndef approx_cummax(x, axis, exclusive=False, reverse=False):\n \"\"\"Approximate the cummax operation in jax.\"\"\"\n sum_x = tf.math.cumsum(x, axis, exclusive=exclusive, reverse=reverse)\n # return tf.math.cumsum(tf.nn.relu(x), axis, reverse=reverse)\n return sum_x\n\n\ndef get_causal_mask(x, axis, is_strict, upper=False):\n \"\"\"Get attention mask bias (keep a lower triangle).\n\n Args:\n x: input tensor\n axis: across which dim to make mask\n is_strict: if True, the diagonal will be masked out as well.\n upper: upper or lower triangle\n\n Returns:\n mask: tensor of {0, -1e9} ^ (x.shape[axis], x.shape[axis])\n \"\"\"\n seq_len = tf.shape(x)[axis]\n if is_strict:\n if upper:\n mask = tf.linalg.band_part(\n tf.ones([seq_len, seq_len], dtype=x.dtype),\n num_lower=-1, num_upper=0)\n else:\n mask = tf.linalg.band_part(\n tf.ones([seq_len, seq_len], dtype=x.dtype),\n num_lower=0, num_upper=-1)\n else:\n if upper:\n mask = 1.0 - tf.linalg.band_part(\n tf.ones([seq_len, seq_len], dtype=x.dtype),\n num_lower=0, num_upper=-1)\n else:\n mask = 1.0 - tf.linalg.band_part(\n tf.ones([seq_len, seq_len], dtype=x.dtype),\n num_lower=-1, num_upper=0)\n mask = -1e9 * mask\n return mask\n\n\ndef pooling_summary(x, axis, local_summary, keepdims=False):\n \"\"\"Perform a cheap pooling summary of a span.\n\n Args:\n x: input tensor\n axis: over which axis to summarize\n local_summary: str of format activation-pooling, choose\n from {relu, identity}-{max, sum, mean}\n keepdims: whether to keep the summarized singleton axis.\n\n Returns:\n y: the same shape as x for other axis,\n except y.shape[axis] = 1 if keepdims=True,\n otherwise y.rank = x.rank + 1\n \"\"\"\n act, pool = local_summary.split('-')\n if act == 'relu':\n x = tf.nn.relu(x)\n elif act == 'identity':\n pass\n elif act == 'deepset':\n x = ops.trail_dense(x, x.shape.as_list()[-1], bias=False)\n x = tf.nn.relu(x)\n else:\n raise ValueError('Unsupported activation: %s' % act)\n if pool == 'mean':\n x = tf.math.reduce_mean(x, axis=axis, keepdims=keepdims)\n elif pool == 'max':\n x = tf.math.reduce_max(x, axis=axis, keepdims=keepdims)\n elif pool == 'sum':\n x = tf.math.reduce_sum(x, axis=axis, keepdims=keepdims)\n else:\n raise ValueError('Unsupported pooling: %s' % pool)\n return x\n\n\ndef axial_mixture_unidir(x, config, is_training=True, causal=True):\n \"\"\"Full attention matrix with axial pattern as local and mixture for global summary.\"\"\"\n del is_training\n assert causal\n bsize = x.shape[0]\n query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size,\n num_heads=config.num_heads, bias=config.dense_use_bias)\n head_dim = config.model_size // config.num_heads\n assert config.max_seq_len % config.max_seg_len == 0\n num_seg = config.max_seq_len // config.max_seg_len\n cur_query = tf.reshape(query, [bsize,\n num_seg,\n config.max_seg_len,\n config.num_heads,\n head_dim])\n cur_key = tf.reshape(key, cur_query.shape)\n cur_val = tf.reshape(value, cur_query.shape)\n\n col_logit_expr = 'BSUNK,BTUNK->BUNST'\n col_attn_expr = 'BUNST,BTUNK->BSUNK'\n col_strict_mask = get_causal_mask(cur_query,\n axis=1,\n is_strict=True)[tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n row_logit_expr = 'BUSNK,BUTNK->BUNST'\n row_attn_expr = 'BUNST,BUTNK->BUSNK'\n row_mask = get_causal_mask(cur_query,\n axis=2,\n is_strict=False)[tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n col_logits = tf.einsum(col_logit_expr, cur_query, cur_key) + col_strict_mask\n row_logits = tf.einsum(row_logit_expr, cur_query, cur_key) + row_mask\n\n ###################\n col_up2down_query = approx_cummax(cur_query, axis=1)\n col_up2down_key = shift_right(approx_cummax(cur_key, axis=1), axis=1)\n col_mask = get_causal_mask(\n cur_query, axis=1, is_strict=False)[tf.newaxis, tf.newaxis,\n tf.newaxis, :, :]\n col_up2down_logits = tf.einsum(col_logit_expr, col_up2down_query,\n cur_key) + col_mask\n col_up2down_attn_weights = attention.float32_softmax(\n col_up2down_logits, axis=-1)\n col_up2down_summary = tf.einsum(col_attn_expr, col_up2down_attn_weights,\n cur_val)\n col_up2down_summary = shift_right(col_up2down_summary, axis=1)\n\n row_only_myself_mask = tf.eye(tf.shape(cur_query)[2], dtype=cur_query.dtype)[tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n row_without_myself_mask = -1e9 * row_only_myself_mask\n all_maskout = tf.cast(tf.fill(row_without_myself_mask.shape, -1e9), cur_query.dtype)\n row_without_myself_mask = tf.concat([all_maskout] + [row_without_myself_mask] * (cur_query.shape[1] - 1),\n axis=1)\n previous_row_logits = tf.einsum(row_logit_expr, cur_query, col_up2down_key) + row_without_myself_mask\n ###################\n\n row_left2right_query = approx_cummax(cur_query, axis=2)\n row_left2right_key = shift_right(approx_cummax(cur_key, axis=2), axis=2)\n row_left2right_logits = tf.einsum(row_logit_expr, row_left2right_query,\n cur_key) + row_mask\n row_left2right_attn_weights = attention.float32_softmax(\n row_left2right_logits, axis=-1)\n row_left2right_summary = tf.einsum(row_attn_expr, row_left2right_attn_weights,\n cur_val)\n row_left2right_summary = shift_right(row_left2right_summary, axis=2)\n\n all_maskout = tf.cast(tf.fill(col_strict_mask.shape, -1e9), cur_query.dtype)\n col_strict_without_first_mask = tf.concat(\n [all_maskout] + [col_strict_mask] * (cur_query.shape[2] - 1), axis=1)\n top_left_col_logits = tf.einsum(\n col_logit_expr, cur_query,\n row_left2right_key) + col_strict_without_first_mask\n ###################\n\n row_right2left_query = approx_cummax(cur_query, axis=2, reverse=True)\n row_right2left_key = shift_left(\n approx_cummax(cur_key, axis=2, reverse=True), axis=2)\n row_upper_mask = get_causal_mask(\n cur_query, axis=2, is_strict=False, upper=True)[tf.newaxis, tf.newaxis,\n tf.newaxis, :, :]\n row_right2left_logits = tf.einsum(row_logit_expr, row_right2left_query,\n cur_key) + row_upper_mask\n row_right2left_attn_weights = attention.float32_softmax(\n row_right2left_logits, axis=-1)\n row_right2left_summary = tf.einsum(row_attn_expr, row_right2left_attn_weights,\n cur_val)\n row_right2left_summary = shift_left(row_right2left_summary, axis=2)\n col_strict_without_last_mask = tf.concat(\n [col_strict_mask] * (cur_query.shape[2] - 1) + [all_maskout], axis=1)\n top_right_col_logits = tf.einsum(\n col_logit_expr, cur_query,\n row_right2left_key) + col_strict_without_last_mask\n ###################\n\n joint_logits = tf.concat([\n tf.transpose(col_logits, perm=[0, 3, 2, 1, 4]), row_logits,\n previous_row_logits,\n tf.transpose(top_left_col_logits, perm=[0, 3, 2, 1, 4]),\n tf.transpose(top_right_col_logits, perm=[0, 3, 2, 1, 4])\n ],\n axis=-1)\n attn_weights = attention.float32_softmax(joint_logits, axis=-1)\n col_att, row_att, previous_row_att, top_left_col_att, top_right_col_att = tf.split(attn_weights,\n [num_seg,\n config.max_seg_len,\n config.max_seg_len,\n num_seg,\n num_seg], axis=-1)\n col_att = tf.transpose(col_att, [0, 3, 2, 1, 4])\n top_left_col_att = tf.transpose(top_left_col_att, [0, 3, 2, 1, 4])\n top_right_col_att = tf.transpose(top_right_col_att, [0, 3, 2, 1, 4])\n col_merged = tf.einsum(col_attn_expr, col_att, cur_val)\n row_merged = tf.einsum(row_attn_expr, row_att, cur_val)\n previous_row_merged = tf.einsum(row_attn_expr, previous_row_att,\n col_up2down_summary)\n top_left_merged = tf.einsum(col_attn_expr, top_left_col_att,\n row_left2right_summary)\n top_right_merged = tf.einsum(col_attn_expr, top_right_col_att,\n row_right2left_summary)\n\n joint_merged = tf.reshape(\n col_merged + row_merged + previous_row_merged + top_left_merged +\n top_right_merged,\n [bsize, num_seg * config.max_seg_len, config.num_heads, head_dim])\n output = ops.trail_dense(joint_merged, config.model_size, begin_axis=-2)\n return output\n\n\ndef sqrt_fixed_full(x, config, is_training=True, causal=True):\n \"\"\"Full attention matrix with sqrt decomposition.\"\"\"\n bsize = x.shape[0]\n query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size,\n num_heads=config.num_heads,\n bias=config.dense_use_bias)\n head_dim = config.model_size // config.num_heads\n assert config.max_seq_len % config.max_seg_len == 0\n num_seg = config.max_seq_len // config.max_seg_len\n cur_query = tf.reshape(query, [-1,\n num_seg,\n config.max_seg_len,\n config.num_heads,\n head_dim])\n with tf.variable_scope('pooling_query'):\n merged_query = pooling_summary(cur_query, axis=2,\n local_summary=config.local_summary,\n keepdims=True)\n cur_key = tf.reshape(key, cur_query.shape)\n cur_val = tf.reshape(value, cur_query.shape)\n span_val = attention.dot_product_attention(merged_query,\n cur_key,\n cur_val,\n is_training=is_training,\n attn_axis=1,\n dropatt=config.dropatt)\n span_val = tf.squeeze(span_val, axis=2)\n with tf.variable_scope('pooling_key'):\n span_key = pooling_summary(cur_key, axis=2,\n local_summary=config.local_summary,\n keepdims=False)\n local_logits = tf.einsum('bsqhd,bskhd->bsqhk', cur_query, cur_key)\n if causal:\n local_mask = get_causal_mask(cur_query, axis=2, is_strict=False)\n local_mask = tf.expand_dims(local_mask, axis=-2)\n local_logits += local_mask\n prev_logits = tf.einsum('bqhd,bkhd->bqhk', query, span_key)\n if causal:\n prev_mask = get_causal_mask(cur_query, axis=1, is_strict=True)\n prev_mask = tf.repeat(prev_mask, [config.max_seg_len] * num_seg, axis=0)\n prev_logits += tf.expand_dims(prev_mask, axis=1)\n joint_logits = tf.concat([tf.reshape(local_logits,\n [bsize, config.max_seq_len,\n config.num_heads, -1]),\n prev_logits], axis=-1)\n attn_weights = attention.float32_softmax(joint_logits, axis=-1)\n local_att, prev_att = tf.split(attn_weights, [config.max_seg_len, num_seg],\n axis=-1)\n if is_training:\n local_att = tf.nn.dropout(local_att, rate=config.dropatt)\n local_att = tf.reshape(local_att, [bsize, num_seg,\n config.max_seg_len,\n config.num_heads,\n config.max_seg_len])\n local_merged = tf.einsum('bsqhk,bskhd->bsqhd', local_att, cur_val)\n prev_merged = tf.einsum('bqhk,bkhd->bqhd', prev_att, span_val)\n joint_merged = prev_merged + tf.reshape(local_merged, prev_merged.shape)\n output = ops.trail_dense(joint_merged, config.model_size, begin_axis=-2)\n return output\n\n\ndef axial_rowmajor(x, config, is_training=True, causal=True):\n \"\"\"Full attention matrix with sqrt decomposition.\"\"\"\n bsize = x.shape[0]\n seq_len = x.shape.as_list()[1]\n head_dim = config.model_size // config.num_heads\n assert seq_len % config.max_seg_len == 0\n num_seg = seq_len // config.max_seg_len\n x_sqr = tf.reshape(x,\n [bsize, num_seg, config.max_seg_len, config.model_size])\n q_row_local, key_row_local, value_row_local = attention.get_qkv(\n x_sqr, x_sqr, x_sqr, hidden_size=config.model_size,\n num_heads=config.num_heads, bias=config.dense_use_bias)\n local_logits = tf.einsum('bsqhd,bskhd->bsqhk', q_row_local, key_row_local)\n row_probs = attention.float32_softmax(local_logits, axis=-1)\n if is_training:\n row_probs = tf.nn.dropout(row_probs, rate=config.dropatt)\n\n row_attn_out = tf.einsum('bsqhk,bskhd->bsqhd', row_probs, value_row_local)\n if config.row_summary == 'none':\n key_row = key_row_local\n elif config.row_summary in ['wsum', 'proj', 'wsum_proj']:\n if 'wsum' in config.row_summary:\n pre_summary = tf.einsum('bsqhk,bskhd->bsqhd', row_probs, key_row_local)\n else:\n pre_summary = row_attn_out\n if 'proj' in config.row_summary:\n with tf.variable_scope('rowmajor_param_post'):\n key_row = ops.trail_dense(pre_summary, config.model_size, begin_axis=-2,\n bias=config.dense_use_bias)\n key_row = ops.postprocess(x_sqr, key_row, config, is_training)\n _, key_row = ops.preprocess(key_row, config)\n key_row = ops.trail_dense(key_row, [config.num_heads, head_dim],\n bias=config.dense_use_bias)\n else:\n key_row = pre_summary\n else:\n raise ValueError('Unknown row summary %s' % config.row_summary)\n if causal:\n local_mask = get_causal_mask(q_row_local, axis=2, is_strict=False)\n local_logits += local_mask[:, tf.newaxis, :]\n\n global_logits = tf.einsum('bqlhd,bklhd->bqlhk', q_row_local, key_row)\n if causal:\n global_mask = get_causal_mask(q_row_local, axis=1, is_strict=True)\n global_logits += global_mask[:, tf.newaxis, tf.newaxis, :]\n # (bsize, num_seg, seg_len, n_head, seg_len + num_seg)\n joint_logits = tf.concat([local_logits, global_logits], axis=-1)\n attn_probs = attention.float32_softmax(joint_logits, axis=-1)\n local_att, global_att = tf.split(attn_probs,\n [config.max_seg_len, num_seg],\n axis=-1)\n if is_training:\n local_att = tf.nn.dropout(local_att, rate=config.dropatt)\n local_merged = tf.einsum('bsqhk,bskhd->bsqhd', local_att, value_row_local)\n global_merged = tf.einsum('bqlhv,bvlhd->bqlhd', global_att, row_attn_out)\n joint_merged = tf.reshape(local_merged + global_merged,\n [bsize, seq_len,\n config.num_heads, head_dim])\n output = ops.trail_dense(joint_merged, config.model_size,\n begin_axis=-2, bias=config.dense_use_bias)\n return output\n\n\ndef axial_mixture_bidir(x, config, is_training=True, causal=False):\n \"\"\"Full attention matrix with axial mixture decomposition.\"\"\"\n assert not causal\n bsize = x.shape[0]\n seq_len = x.shape.as_list()[1]\n head_dim = config.model_size // config.num_heads\n assert seq_len % config.max_seg_len == 0\n num_seg = seq_len // config.max_seg_len\n x_sqr = tf.reshape(x,\n [bsize, num_seg, config.max_seg_len, config.model_size])\n query, key, value = attention.get_qkv(\n x_sqr, x_sqr, x_sqr, hidden_size=config.model_size,\n num_heads=config.num_heads, bias=config.dense_use_bias)\n local_row_logits = tf.einsum('bushd,buthd->bhust', query, key)\n local_col_logits = tf.einsum('bsuhd,btuhd->bhsut', query, key)\n # TODO: add self-mask for local_col_logits\n\n span_attn_fn = functools.partial(attention.dot_product_attention,\n key_heads=key,\n value_heads=value,\n is_training=is_training,\n dropatt=config.dropatt)\n\n # === top-down summary ===\n col_query_topdown = approx_cummax(query, 1, exclusive=True)\n col_key_topdown = approx_cummax(key, 1, exclusive=True)\n col_t2d_mask = get_causal_mask(x_sqr, axis=1, is_strict=True)\n col_t2d_val = span_attn_fn(query_heads=col_query_topdown,\n attn_axis=0,\n attn_bias=col_t2d_mask)\n\n # === bottom-up summary ===\n col_query_bottomup = approx_cummax(query, 1, exclusive=True, reverse=True)\n col_key_bottomup = approx_cummax(key, 1, exclusive=True, reverse=True)\n col_b2t_mask = get_causal_mask(x_sqr, axis=1, is_strict=True, upper=True)\n col_b2t_val = span_attn_fn(query_heads=col_query_bottomup,\n attn_axis=0,\n attn_bias=col_b2t_mask)\n\n # === left2right summary ===\n row_query_left2right = approx_cummax(query, 2, exclusive=True)\n row_key_left2right = approx_cummax(key, 2, exclusive=True)\n row_l2r_mask = get_causal_mask(x_sqr, axis=2, is_strict=True)\n row_l2r_val = span_attn_fn(query_heads=row_query_left2right,\n attn_axis=1,\n attn_bias=row_l2r_mask)\n\n # === right2left summary ===\n row_query_right2left = approx_cummax(query, 2, exclusive=True, reverse=True)\n row_key_right2left = approx_cummax(key, 2, exclusive=True, reverse=True)\n row_r2l_mask = get_causal_mask(x_sqr, axis=2, is_strict=True, upper=True)\n row_r2l_val = span_attn_fn(query_heads=row_query_right2left,\n attn_axis=1,\n attn_bias=row_r2l_mask)\n\n global_t2d_logits = tf.einsum('bushd,buthd->bhust', query, col_key_topdown)\n global_b2t_logits = tf.einsum('bushd,buthd->bhust', query, col_key_bottomup)\n global_l2r_logits = tf.einsum('bsuhd,btuhd->bhsut', query, row_key_left2right)\n global_r2l_logits = tf.einsum('bsuhd,btuhd->bhsut', query, row_key_right2left)\n joint_logits = tf.concat([local_row_logits, local_col_logits,\n global_t2d_logits, global_b2t_logits,\n global_l2r_logits, global_r2l_logits], axis=-1)\n attn_probs = attention.float32_softmax(joint_logits, axis=-1)\n prow, pcol, pt2d, pb2t, pl2r, pr2l = tf.split(\n attn_probs, [config.max_seg_len, num_seg, config.max_seg_len,\n config.max_seg_len, num_seg, num_seg], axis=-1)\n mrow = tf.einsum('bhust,buthd->bushd', prow, value)\n mcol = tf.einsum('bhsut,btuhd->bsuhd', pcol, value)\n mt2d = tf.einsum('bhust,buthd->bushd', pt2d, col_t2d_val)\n mb2t = tf.einsum('bhust,buthd->bushd', pb2t, col_b2t_val)\n ml2r = tf.einsum('bhsut,btuhd->bsuhd', pl2r, row_l2r_val)\n mr2l = tf.einsum('bhsut,btuhd->bsuhd', pr2l, row_r2l_val)\n joint_merged = mrow + mcol + mt2d + mb2t + ml2r + mr2l\n joint_merged = tf.reshape(joint_merged,\n [bsize, seq_len, config.num_heads, head_dim])\n output = ops.trail_dense(joint_merged, config.model_size,\n begin_axis=-2, bias=config.dense_use_bias)\n return output\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Input function hook for PPO TF estimator.\n\nFor the PPO algorithm, see https://arxiv.org/abs/1707.06347.\n\"\"\"\nfrom absl import logging\nimport gin\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom polish.ppo import ppo_loss\nfrom polish.utils import distributions\nfrom polish.utils import host_call_fn\nfrom polish.utils import tf_layers\nfrom tensorflow.contrib import tpu as contrib_tpu\n\nlogging.set_verbosity(logging.INFO)\n\n\[email protected]\nclass PpoModelFn(object):\n \"\"\"Main class for model function used in tf.estimator.\n\n Attributes:\n policy_loss: Proximal Policy Optimization (PPO) policy loss.\n value_loss: PPO value loss.\n entropy_loss: PPO entropy loss.\n imitation_kl_divergence: The KL-divergence of action distributions between\n the policy and MCTS.\n total_loss: PPO total loss.\n clipfrac: Fraction of examples in a batch clipped by PPO.\n approxkl: `Approximate` KL divergence between new policy and old policy.\n This is an estimate (approximate) of the KL divergence, since we compute\n the KL divergence using the samples drawn from the new and\n old distributions.\n total_params: Total trainable parameters.\n train_op: Training operation.\n mean_new: Mean of new policy distribution.\n logstd_new: Log standard deviation of new policy distribution.\n mean_old: Mean of old policy distribution.\n logstd_old: Log standard deviation of old policy distribution.\n value_new: state-value from the latest trained state-value network.\n kl_divergence: Kullback-Leibler divergence between new and old policy.\n entropy: Entropy of the new policy.\n global_step: Global step of training.\n policy_ratio: the ratio between new policy and old policy.\n last_iteration_mcts_enable: Track the sampling type (PPO sampling/MCTS) in\n the process of training. That is, whether in the last iteration of\n training, we use PPO sampling (False) or MCTS sampling (True).\n mcts_sampling_enable: If True, it means that the current batch\n is generated by MCTS.\n mean_mse_loss: Mean squared error between the mean value of\n policy distribuiton and the mean value returned by MCTS given a state.\n logstd_mse_loss: Mean squared error between log of standard deviation value\n of the policy distribuiton and the log of standard deviation value\n returned by MCTS given a state.\n \"\"\"\n\n def __init__(\n self,\n env_action_space=2,\n iterations_per_loop=320,\n num_timesteps=1000000,\n max_horizon=2048,\n learning_rate=3e-4,\n use_tpu=False,\n ppo2_enable=True,\n policy_coeff=1.0,\n value_coeff=0.5,\n entropy_coeff=0.0,\n tpu_num_shards=8,\n mse_loss_coeff=0.0,\n warmstart_file=None,\n policy_hidden_layer_size=64,\n value_hidden_layer_size=64):\n \"\"\"Creates a model function for PPO algorithm.\n\n The default values for all the parameters are from PPO paper.\n\n Args:\n env_action_space: The size of environment action space.\n iterations_per_loop: Number of steps to run on TPU before outfeeding\n metrics to the CPU. If the number of iterations in the loop would exceed\n the number of train steps, the loop will exit before reaching\n --iterations_per_loop. The larger this value is, the higher the\n utilization on the TPU.\n num_timesteps: Total number of timesteps. Defines the total number of\n samples taken from the environment during the whole process of training.\n max_horizon: Maximum number of samples taken from the environment before\n starting training.\n learning_rate: Initial learning rate value. Note that the actual learning\n rate is linearly decayed.\n use_tpu: If True, training occurs on TPU.\n ppo2_enable: If True, we use the next version of PPO algorithm, known as\n PPO2. In this version, not only does the probability ratio get clipped,\n but also the clipping is performed on the value loss.\n For more information:\n https://github.com/openai/baselines/tree/master/baselines/ppo2.\n policy_coeff: Policy loss coefficient in the total loss calculation.\n value_coeff: Value loss coefficient in the total loss calculation.\n entropy_coeff: Entropy loss coefficient in the total loss calculation.\n tpu_num_shards: Number of TPU shards.\n mse_loss_coeff: The coefficient for Mean Squared Error (MSE) loss.\n warmstart_file: If not None, we restore the weights for the parameters in\n `newpolicy` scope from this file. `newpolicy` scope contains both\n policy and value network.\n policy_hidden_layer_size: The size of hidden layer in policy network.\n Currently, this value is used for both of the hidden layers.\n value_hidden_layer_size: The size of hidden layer in value network.\n Currently, this value is used for both of the hidden layers.\n \"\"\"\n self.policy_loss = 0\n self.value_loss = 0\n self.entropy_loss = 0\n self.total_loss = 0\n self.clipfrac = 0\n self.approxkl = 0\n self.policy_ratio = 0\n\n self.total_params = None\n self.train_op = None\n\n self.mean_new = None\n self.logstd_new = None\n self.mean_old = None\n self.logstd_old = None\n self.value_new = None\n\n self.kl_divergence = None\n self.entropy = 0\n\n self.global_step = None\n\n self._decayed_learning_rate = None\n\n self._env_action_space = env_action_space\n self._iterations_per_loop = iterations_per_loop\n self._num_timesteps = num_timesteps\n self._max_horizon = max_horizon\n self._learning_rate = learning_rate\n self._use_tpu = use_tpu\n self._ppo2_enable = ppo2_enable\n self._policy_coeff = policy_coeff\n self._value_coeff = value_coeff\n self._entropy_coeff = entropy_coeff\n self._tpu_num_shards = tpu_num_shards\n\n self._mse_loss_coeff = mse_loss_coeff\n self._warmstart_file = warmstart_file\n\n self.last_iteration_mcts_enable = False\n self._mcts_global_step = 0\n\n self._policy_hidden_layer_size = policy_hidden_layer_size\n self._value_hidden_layer_size = value_hidden_layer_size\n\n def __call__(self, features, labels, mode, params):\n return self.model_fn(features, labels, mode, params)\n\n def model_inference_fn_ppo(self, features, prefix):\n \"\"\"Builds just the inference part of the model graph.\n\n Args:\n features: input features tensor.\n prefix: prefix to be added to the network.\n\n Returns:\n (value, var, mean) tuple of tensors.\n \"\"\"\n # Policy Network\n features = tf.layers.flatten(features)\n with tf.variable_scope(prefix + 'policy', reuse=tf.AUTO_REUSE):\n policy_1 = tf.tanh(\n tf_layers.fc(\n tensor_in=features,\n num_hidden=self._policy_hidden_layer_size,\n scope_name='/policy_1',\n init_scale=np.sqrt(2)))\n policy_2 = tf.tanh(\n tf_layers.fc(\n tensor_in=policy_1,\n num_hidden=self._policy_hidden_layer_size,\n scope_name='/policy_2',\n init_scale=np.sqrt(2)))\n mean = tf_layers.fc(\n tensor_in=policy_2,\n num_hidden=self._env_action_space,\n scope_name='/mean',\n init_scale=0.01,\n init_bias=0.0)\n logstd_var = tf.get_variable(\n name=prefix + '_logstd',\n shape=[1, self._env_action_space],\n initializer=tf.zeros_initializer())\n # Evaluate logstd_var and broadcast to have a same shape as mean\n logstd = tf.multiply(logstd_var, 1.0)\n\n value_1 = tf.tanh(\n tf_layers.fc(\n tensor_in=features,\n num_hidden=self._value_hidden_layer_size,\n scope_name='/value_1',\n init_scale=np.sqrt(2)))\n value_2 = tf.tanh(\n tf_layers.fc(\n tensor_in=value_1,\n num_hidden=self._value_hidden_layer_size,\n scope_name='/value_2',\n init_scale=np.sqrt(2)))\n value = tf_layers.fc(\n tensor_in=value_2, num_hidden=1, scope_name='/value')[:, 0]\n\n return value, logstd, mean\n\n def learning_rate_update_true_fn(self):\n \"\"\"The function which is performed if the predicate is true.\n\n The predicate that calls this function is defined in 'update_learning_rate'.\n\n Returns:\n The current global step.\n \"\"\"\n return tf.train.get_global_step()\n\n def learning_rate_update_false_fn(self):\n \"\"\"The function which is performed if the predicate is false.\n\n The predicate that calls this function is defined in 'update_learning_rate'.\n\n Returns:\n A type-casted value of `_mcts_global_step` to int64.\n `_mcts_global_step` is the global step at which MCTS algorithm starts.\n The type casting is necessary as the type of returned tensor in `true_fn`\n is an int.64.\n \"\"\"\n return tf.cast(self._mcts_global_step, tf.int64)\n\n def update_learning_rate(self):\n \"\"\"Update the learning rate with a decaying factor.\n \"\"\"\n self._current_global_step = tf.cond(\n tf.equal(self.mcts_sampling_enable,\n True), lambda: self._mcts_global_step, lambda: 0)\n\n self._current_global_step = tf.cast(self._current_global_step, tf.int64)\n\n update = (tf.train.get_global_step() -\n self._current_global_step) // self._iterations_per_loop + 1\n current_frac = self._num_timesteps // self._max_horizon\n update = tf.cast(update, tf.float32)\n current_frac = tf.cast(current_frac, tf.float32)\n frac = 1.0 - (update - 1.0) / current_frac\n self._decayed_learning_rate = self._learning_rate * frac\n self._mcts_global_step = tf.cond(\n tf.not_equal(self.mcts_sampling_enable,\n self.last_iteration_mcts_enable),\n self.learning_rate_update_true_fn, self.learning_rate_update_false_fn)\n self.last_iteration_mcts_enable = self.mcts_sampling_enable\n\n def build_training_op(self, loss):\n \"\"\"Get training operation.\n\n Args:\n loss: a loss function for training.\n\n Define the optimization operation and perform gradient calculation for both\n TPU/Non-TPU training.\n\n Returns:\n Computed gradient.\n \"\"\"\n adam_optimizer = tf.train.AdamOptimizer(\n learning_rate=self._decayed_learning_rate, epsilon=1e-5)\n if self._use_tpu:\n # If we use TPUs, reduce_mean runs on each chip separately and by default\n # only the loss of the first chip is reported.\n #\n # You can either:\n # - execute this if, which synchronizes the losses\n # across the chips to obtain the full loss on all samples.\n # - or remove this section, gaining some performance and getting the\n # loss only from the first chip.\n # compute gradients perform averaging of the loss\n adam_optimizer = tf.tpu.CrossShardOptimizer(adam_optimizer)\n\n tpu_sum_loss = contrib_tpu.cross_replica_sum(loss / self._tpu_num_shards)\n\n grads_and_vars = adam_optimizer.compute_gradients(tpu_sum_loss,\n self.total_params)\n grads, var = zip(*grads_and_vars)\n sum_grads = []\n sum_vars = []\n for (grad, var) in grads_and_vars:\n if grad is None:\n sum_grads.append(grad)\n sum_vars.append(var)\n else:\n sum_grads.append(\n contrib_tpu.cross_replica_sum(grad) / self._tpu_num_shards)\n sum_vars.append(var)\n # calculate sum of grads\n norm_grads, _ = tf.clip_by_global_norm(sum_grads, 0.5)\n grads_and_vars = list(zip(norm_grads, sum_vars))\n else:\n grads_and_vars = adam_optimizer.compute_gradients(loss,\n self.total_params)\n grads, var = zip(*grads_and_vars)\n norm_grads, _ = tf.clip_by_global_norm(grads, 0.5)\n grads_and_vars = list(zip(norm_grads, var))\n\n return adam_optimizer.apply_gradients(\n grads_and_vars, global_step=tf.train.get_global_step())\n\n def calc_normalized_advantage(self, return_tensor, value_tensor):\n \"\"\"Compute General Advantage Estimation (GAE) and normalize it.\n\n Note that, the advantage calculation-normalization is performed for a batch\n of data.\n\n Args:\n return_tensor: The discounted accumulated reward (return) calculated\n for the given rollout trajectory.\n value_tensor: The value for each state for the given rollout trajectory.\n\n Returns:\n Returns the normalized General Advantage Estimation (GAE).\n \"\"\"\n batch_advantage = return_tensor - value_tensor\n batch_advantage_std = tf.keras.backend.std(batch_advantage)\n batch_advantage_mean = tf.reduce_mean(batch_advantage)\n batch_advantage_norm = (batch_advantage - batch_advantage_mean) / (\n batch_advantage_std + 1e-8)\n return batch_advantage_norm\n\n def create_host_call_fn(self, params):\n \"\"\"Create host call function.\n\n `host_call` function is later called by TPU estimator to\n send some metrics to host for logging.\n\n Args:\n params: A dictionary of hyperparameters passed to the tf.estimator.\n\n Returns:\n A host call function that generates a set of tf summaries.\n \"\"\"\n names_and_tensors = [\n ('Batch_Params/mean_mse_loss', self.mean_mse_loss),\n ('Batch_Params/logstd_mse_loss', self.logstd_mse_loss),\n ('Batch_Params/policy_loss', self.policy_loss),\n ('Batch_Params/mcts_enable', self.mcts_sampling_enable),\n ('Batch_Params/value_loss', self.value_loss),\n ('Batch_Params/policy_entropy', self.entropy_loss),\n ('Batch_Params/imitation_kl_divergence', self.imitation_kl_divergence),\n ('Batch_Params/clip_fraction', self.clipfrac),\n ('Batch_Params/max_ratio', tf.reduce_max(self.policy_ratio)),\n ('Batch_Params/min_ratio', tf.reduce_min(self.policy_ratio)),\n ('Batch_Params/mean_ratio', tf.reduce_mean(self.policy_ratio)),\n ('Batch_Params/approx_kl', self.approxkl),\n ('Learning_Rate/learning_rate', self._decayed_learning_rate),\n ('Learning_Rate/global_step', tf.train.get_global_step())\n ]\n\n return host_call_fn.build_host_call_fn_every_n_global_steps(\n params=params,\n names_and_tensors=names_and_tensors,\n n=self._iterations_per_loop)\n\n def compute_total_loss(self, pd_new, pd_old, value_tensor, return_tensor,\n batch_advantage_norm,\n policy_old_neg_logprob_tensor,\n policy_action_tensor):\n \"\"\"Defines the total loss function.\n\n Args:\n pd_new: The current policy distribution\n (a multivariate normal distribution). This policy distribution gets\n updated in the course of training.\n pd_old: The old policy distribution that we use during sampling the\n trajectory (a multivariate normal distribution).\n value_tensor: The values associated to the rollout trajectory.\n return_tensor: The return values computed for the rollout trajectory.\n batch_advantage_norm: The normalized advantage tensor computed for a\n batch of data. For advantage calculation, we use generalized\n advantage estimation (GAE) formula.\n policy_old_neg_logprob_tensor: The negative log probabilities from the\n policy rollouts.\n policy_action_tensor: The actions from the policy rollouts.\n \"\"\"\n # Policy loss\n ppo_policy_loss_out = ppo_loss.ppo_policy_loss(\n neg_logprobs_old=policy_old_neg_logprob_tensor,\n actions=policy_action_tensor,\n advantages=batch_advantage_norm,\n dist_new=pd_new,\n mcts_sampling=self.mcts_sampling_enable)\n\n (self.policy_loss, self.approxkl, self.clipfrac,\n self.policy_ratio) = ppo_policy_loss_out\n\n # Value Loss\n if self._ppo2_enable:\n self.value_loss = ppo_loss.ppo2_value_loss(\n value_old=value_tensor,\n pred_value=self.value_new,\n returns=return_tensor)\n else:\n self.value_loss = ppo_loss.ppo1_value_loss(\n pred_value=self.value_new, returns=return_tensor)\n\n # MSE loss between mean and standard deviations\n self.mean_mse_loss, self.logstd_mse_loss = ppo_loss.l2_norm_policy_loss(\n policy_mean=self.mean_new,\n policy_logstd=self.logstd_new,\n mcts_mean=self.mean_old,\n mcts_logstd=self.logstd_old)\n\n mcts_dist = distributions.MultiVariateNormalDiag(\n mean=self.mean_old, logstd=self.logstd_old)\n policy_dist = distributions.MultiVariateNormalDiag(\n mean=self.mean_new, logstd=self.logstd_new)\n self.imitation_kl_divergence = tf.reduce_mean(\n policy_dist.kl_divergence(mcts_dist))\n # Calculate KL divergence and entropy of new distribution\n self.kl_divergence = tf.reduce_mean(pd_new.kl_divergence(pd_old))\n self.entropy = pd_new.entropy()\n\n # Calculate entropy loss\n self.entropy_loss = tf.reduce_mean(self.entropy)\n\n # Calulate total loss\n total_loss_ppo = (self._policy_coeff * self.policy_loss) + (\n self._value_coeff * self.value_loss) - (\n self._entropy_coeff * self.entropy_loss)\n\n total_loss_mcts = (self._value_coeff * self.value_loss) + (\n self._mse_loss_coeff *\n (self.imitation_kl_divergence + self.entropy_loss))\n\n self.total_loss = tf.cond(\n tf.equal(self.mcts_sampling_enable,\n True), lambda: total_loss_mcts, lambda: total_loss_ppo)\n\n def model_fn(self, features, labels, mode, params):\n \"\"\"The implementation of PPO algorithm.\n\n Args:\n features: dict from string to tensor with shape\n 'state_tensor': [BATCH_SIZE, env.state_space]\n labels: dict from string to tensor with shape\n 'action_tensor': [BATCH_SIZE, self._env_action_space]\n 'advantage_tensor': [BATCH_SIZE]\n 'returns_tensor': [BATCH_SIZE]\n mode: a tf.estimator.ModeKeys (batchnorm params update for TRAIN only).\n params: (Ignored; needed for compat with TPUEstimator).\n\n Returns:\n tf.estimator.EstimatorSpec with props.\n mode: same as mode arg.\n predictions: dict of tensors\n 'mean': [BATCH_SIZE, self._env_action_space]\n 'logstd': [BATCH_SIZE, self._env_action_space]\n 'value': [BATCH_SIZE]\n 'action': [BATCH_SIZE, self._env_action_space]\n 'neg_logprob': [BATCH_SIZE, self._env_action_space]\n loss: a single value tensor.\n train_op: train op eval_metric_ops return dict of tensors.\n \"\"\"\n\n # Policy network\n network_out = self.model_inference_fn_ppo(features['mcts_features'], 'new')\n self.value_new = network_out[0]\n self.logstd_new = network_out[1]\n self.mean_new = network_out[2]\n\n self.global_step = tf.train.get_or_create_global_step()\n # Sample an action\n pd_new = distributions.MultiVariateNormalDiag(\n mean=self.mean_new, logstd=self.logstd_new)\n action_sample = pd_new.sample()\n action_sample_neg_logprob = pd_new.negative_log_prob(action_sample)\n\n # Used during TF estimator prediction\n if mode == tf.estimator.ModeKeys.PREDICT:\n predictions = {\n 'mean': self.mean_new,\n 'logstd': self.logstd_new,\n 'value': self.value_new,\n 'action': action_sample,\n 'neg_logprob': action_sample_neg_logprob\n }\n pred_estimator = tf.estimator.tpu.TPUEstimatorSpec(\n mode,\n predictions=predictions,\n export_outputs={\n 'ppo_inference':\n tf.estimator.export.PredictOutput({\n 'mean': self.mean_new,\n 'logstd': self.logstd_new,\n 'value': self.value_new,\n 'action': action_sample,\n 'neg_logprob': action_sample_neg_logprob\n })\n })\n return pred_estimator.as_estimator_spec()\n\n # Placeholder\n self.mcts_sampling_enable = tf.reduce_all(labels['mcts_enable_tensor'])\n\n self.mean_old = labels['mean_tensor']\n self.logstd_old = labels['logstd_tensor']\n pd_old = distributions.MultiVariateNormalDiag(\n mean=self.mean_old, logstd=self.logstd_old)\n\n batch_advantage_norm = self.calc_normalized_advantage(\n return_tensor=labels['policy_return_tensor'],\n value_tensor=labels['policy_value_tensor'])\n\n self.compute_total_loss(pd_new, pd_old, labels['value_tensor'],\n labels['return_tensor'], batch_advantage_norm,\n labels['policy_old_neg_logprob_tensor'],\n labels['policy_action_tensor'])\n # Update learning rate\n self.update_learning_rate()\n\n # Build training operation\n self.total_params = tf.trainable_variables(scope='newpolicy')\n\n train_ops = self.build_training_op(self.total_loss)\n\n host_call = self.create_host_call_fn(params)\n\n if mode != tf.estimator.ModeKeys.TRAIN:\n raise ValueError('Estimator mode should be train at this point.')\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n # Setup fine tune scaffold\n # The scaffold here is used to restore the weights from _warmstart_file.\n # If _warmstart_file is None, the training starts from the beginning.\n if self._warmstart_file:\n logging.info('Warmstart')\n def tpu_scaffold():\n # restore all the variables\n tf.init_from_checkpoint(self._warmstart_file,\n {'newpolicy/': 'newpolicy/'})\n return tf.train.Scaffold()\n scaffold_fn = tpu_scaffold\n else:\n scaffold_fn = None\n\n tpu_estimator_spec = tf.estimator.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=self.total_loss,\n train_op=train_ops,\n host_call=host_call,\n scaffold_fn=scaffold_fn)\n if self._use_tpu:\n return tpu_estimator_spec\n else:\n return tpu_estimator_spec.as_estimator_spec()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copyright 2022 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# Usage: configure.py [--quiet] [--no-deps]\n#\n# Options:\n# --quiet Give less output.\n# --no-deps Don't install Python dependencies\n\"\"\"Configures ScaNN to be built from source.\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\n\n_BAZELRC = \".bazelrc\"\n_BAZEL_QUERY = \".bazel-query.sh\"\n\n\n# Writes variables to bazelrc file\ndef write_to_bazelrc(line):\n with open(_BAZELRC, \"a\") as f:\n f.write(line + \"\\n\")\n\n\ndef write_action_env(var_name, var):\n write_to_bazelrc('build --action_env %s=\"%s\"' % (var_name, str(var)))\n with open(_BAZEL_QUERY, \"a\") as f:\n f.write('{}=\"{}\" '.format(var_name, var))\n\n\ndef get_input(question):\n try:\n return input(question)\n except EOFError:\n return \"\"\n\n\ndef generate_shared_lib_name(namespec):\n \"\"\"Converts the linkflag namespec to the full shared library name.\"\"\"\n # Assume Linux for now\n return namespec[1][3:]\n\n\ndef create_build_configuration():\n \"\"\"Main function to create build configuration.\"\"\"\n print()\n print(\"Configuring ScaNN to be built from source...\")\n\n pip_install_options = [\"--upgrade\"]\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--quiet\", action=\"store_true\", help=\"Give less output.\")\n parser.add_argument(\n \"--no-deps\",\n action=\"store_true\",\n help=\"Do not check and install Python dependencies.\",\n )\n args = parser.parse_args()\n if args.quiet:\n pip_install_options.append(\"--quiet\")\n\n python_path = sys.executable\n with open(\"requirements.txt\") as f:\n required_packages = f.read().splitlines()\n\n print()\n if args.no_deps:\n print(\"> Using pre-installed Tensorflow.\")\n else:\n print(\"> Installing\", required_packages)\n install_cmd = [python_path, \"-m\", \"pip\", \"install\"]\n install_cmd.extend(pip_install_options)\n install_cmd.extend(required_packages)\n subprocess.check_call(install_cmd)\n\n if os.path.isfile(_BAZELRC):\n os.remove(_BAZELRC)\n if os.path.isfile(_BAZEL_QUERY):\n os.remove(_BAZEL_QUERY)\n\n logging.disable(logging.WARNING)\n\n import tensorflow.compat.v2 as tf # pylint: disable=g-import-not-at-top\n\n # pylint: disable=invalid-name\n _TF_CFLAGS = tf.sysconfig.get_compile_flags()\n _TF_LFLAGS = tf.sysconfig.get_link_flags()\n _TF_CXX11_ABI_FLAG = tf.sysconfig.CXX11_ABI_FLAG\n\n _TF_SHARED_LIBRARY_NAME = generate_shared_lib_name(_TF_LFLAGS)\n _TF_HEADER_DIR = _TF_CFLAGS[0][2:]\n _TF_SHARED_LIBRARY_DIR = _TF_LFLAGS[0][2:]\n # pylint: enable=invalid-name\n\n write_action_env(\"TF_HEADER_DIR\", _TF_HEADER_DIR)\n write_action_env(\"TF_SHARED_LIBRARY_DIR\", _TF_SHARED_LIBRARY_DIR)\n write_action_env(\"TF_SHARED_LIBRARY_NAME\", _TF_SHARED_LIBRARY_NAME)\n write_action_env(\"TF_CXX11_ABI_FLAG\", _TF_CXX11_ABI_FLAG)\n\n write_to_bazelrc(\"build --spawn_strategy=standalone\")\n write_to_bazelrc(\"build --strategy=Genrule=standalone\")\n write_to_bazelrc(\"build -c opt\")\n\n print()\n print(\"Build configurations successfully written to\", _BAZELRC)\n print()\n\n with open(_BAZEL_QUERY, \"a\") as f:\n f.write('bazel query \"$@\"')\n\n\nif __name__ == \"__main__\":\n create_build_configuration()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plot_heatmap(pdf_func, out_name, size=3):\n w = 100\n x = np.linspace(-size, size, w)\n y = np.linspace(-size, size, w)\n xx, yy = np.meshgrid(x, y)\n coords = np.stack([xx.flatten(), yy.flatten()]).transpose()\n\n scores = pdf_func(coords)\n a = scores.reshape((w, w))\n\n plt.imshow(a)\n plt.axis('equal')\n plt.axis('off')\n plt.savefig(out_name, bbox_inches='tight')\n plt.close()\n\n\ndef plot_samples(samples, out_name):\n plt.scatter(samples[:, 0], samples[:, 1])\n plt.axis('equal')\n plt.savefig(out_name, bbox_inches='tight')\n plt.close()\n\n\ndef plot_joint(dataset, samples, out_name):\n x = np.max(dataset)\n y = np.max(-dataset)\n z = np.ceil(max((x, y)))\n plt.scatter(dataset[:, 0], dataset[:, 1], c='r', marker='x')\n plt.scatter(samples[:, 0], samples[:, 1], c='b', marker='.')\n plt.legend(['training data', 'ADE sampled'])\n plt.axis('equal')\n plt.xlim(-z, z)\n plt.ylim(-z, z)\n plt.savefig(out_name, bbox_inches='tight')\n plt.close()\n\n fname = out_name.split('/')[-1]\n out_name = '/'.join(out_name.split('/')[:-1]) + '/none-' + fname\n plt.figure(figsize=(8, 8))\n plt.scatter(dataset[:, 0], dataset[:, 1], c='r', marker='x')\n plt.scatter(samples[:, 0], samples[:, 1], c='b', marker='.')\n plt.axis('equal')\n plt.xlim(-z, z)\n plt.ylim(-z, z)\n plt.savefig(out_name, bbox_inches='tight')\n plt.close()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: skip-file\nimport numpy as np\nimport random\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn.parameter import Parameter\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.nn.utils.rnn import pack_sequence, PackedSequence, pad_packed_sequence, pack_padded_sequence\n\nfrom aloe.common.pytorch_util import glorot_uniform, MLP, pad_sequence, MaskedEmbedding\nfrom aloe.rfill.utils.rfill_consts import STR_VOCAB\nfrom torch_scatter import scatter_mean, scatter_max\n\n\nclass AbstractIOEmbed(nn.Module):\n def __init__(self, args):\n super(AbstractIOEmbed, self).__init__()\n self.numPublicIO = args.numPublicIO\n if args.io_agg_type == 'max':\n self.agg_func = lambda x, idx: scatter_max(x, idx, dim=0)[0]\n elif args.io_agg_type == 'mean':\n self.agg_func = lambda x, idx: scatter_mean(x, idx, dim=0)\n else:\n raise NotImplementedError\n\n def io2idx_func(self, x):\n raise NotImplementedError\n\n def padded_inputs(self, int_seqs):\n raise NotImplementedError\n\n def padded_outputs(self, int_seqs):\n raise NotImplementedError\n\n def cook_raw_io(self, inputs_list, outputs_list):\n seq_input_ints = []\n seq_outputs_ints = []\n scatter_idx = []\n for i, (inputs, outputs) in enumerate(zip(inputs_list, outputs_list)):\n for x, y in zip(inputs[:self.numPublicIO], outputs[:self.numPublicIO]):\n seq_input_ints.append(self.io2idx_func(x))\n seq_outputs_ints.append(self.io2idx_func(y))\n scatter_idx += [i] * len(inputs)\n padded_i = self.padded_inputs(seq_input_ints)\n padded_o = self.padded_outputs(seq_outputs_ints)\n scatter_idx = torch.LongTensor(scatter_idx)\n return padded_i, padded_o, scatter_idx\n\n\nclass MLPIOEmbed(AbstractIOEmbed):\n def __init__(self, args, n_hidden=2):\n super(MLPIOEmbed, self).__init__(args)\n self.max_input_len = args.maxInputLength\n self.max_output_len = args.maxOutputLength\n self.vocab = {'unk': 0}\n for i, c in enumerate(STR_VOCAB):\n self.vocab[c] = i + 1\n if args.io_embed_type == 'normal':\n self.input_tok_embed = nn.Embedding(len(self.vocab), 4)\n self.output_tok_embed = nn.Embedding(len(self.vocab), 4)\n else:\n self.input_tok_embed = MaskedEmbedding(len(self.vocab), 4, masked_token=self.vocab['unk'])\n self.output_tok_embed = MaskedEmbedding(len(self.vocab), 4, masked_token=self.vocab['unk'])\n self.embed_merge = MLP(4 * (self.max_input_len + self.max_output_len), [args.embed_dim] * n_hidden,\n nonlinearity=args.act_func,\n act_last=args.act_func)\n self.device = args.device\n\n def io2idx_func(self, x):\n return [self.vocab[c] for c in x] if len(x) else [self.vocab['unk']]\n\n def _padded_io(self, int_seqs, max_len):\n int_seqs = [torch.LongTensor(x) for x in int_seqs]\n padded = pad_sequence(int_seqs, max_len=max_len, batch_first=True)\n return padded\n\n def padded_inputs(self, int_seqs):\n return self._padded_io(int_seqs, max_len=self.max_input_len)\n\n def padded_outputs(self, int_seqs):\n return self._padded_io(int_seqs, max_len=self.max_output_len)\n\n def embed_seq(self, padded, tok_embed):\n tok_embed = tok_embed(padded.data)\n seq_embed = tok_embed.view(padded.shape[0], -1)\n return seq_embed\n\n def forward(self, inputs_list, outputs_list, cooked_data=None):\n if cooked_data is None:\n padded_i, padded_o, scatter_idx = self.cook_raw_io(inputs_list, outputs_list)\n else:\n padded_i, padded_o, scatter_idx = cooked_data.get_ios()\n padded_i = padded_i.to(self.device)\n padded_o = padded_o.to(self.device)\n scatter_idx = scatter_idx.to(self.device)\n\n input_embed = self.embed_seq(padded_i, self.input_tok_embed)\n output_embed = self.embed_seq(padded_o, self.output_tok_embed)\n\n single_io_input = torch.cat((input_embed, output_embed), dim=-1)\n single_io_embed = self.embed_merge(single_io_input)\n ctx_embed = self.agg_func(single_io_embed, scatter_idx)\n return None, None, ctx_embed\n\n\nclass TripletIOEmbed(MLPIOEmbed):\n def __init__(self, args):\n super(MLPIOEmbed, self).__init__(args)\n self.max_output_len = args.maxOutputLength\n self.vocab = {'unk': 0}\n for i, c in enumerate(STR_VOCAB):\n self.vocab[c] = i + 1\n if args.io_embed_type == 'normal':\n self.tok_embed = nn.Embedding(len(self.vocab), 4)\n else:\n self.tok_embed = MaskedEmbedding(len(self.vocab), 4, masked_token=self.vocab['unk'])\n\n self.embed_merge = MLP(4 * 3 * self.max_output_len, [args.embed_dim] * 5,\n nonlinearity=args.act_func,\n act_last=args.act_func)\n self.device = args.device\n\n def padded_inputs(self, int_seqs):\n return self._padded_io(int_seqs, max_len=self.max_output_len)\n\n def forward(self, inputs_list, outputs_list, cooked_data=None):\n if cooked_data is None:\n padded_i, padded_o, scatter_idx = self.cook_raw_io(inputs_list, outputs_list)\n else:\n padded_i, padded_o, scatter_idx = cooked_data.get_ios()\n padded_i = padded_i.to(self.device)\n padded_o = padded_o.to(self.device)\n scatter_idx = scatter_idx.to(self.device)\n input_embed = self.embed_seq(padded_i, self.tok_embed)\n output_embed = self.embed_seq(padded_o, self.tok_embed)\n diff_embed = output_embed - input_embed\n\n single_io_input = torch.cat((input_embed, output_embed, diff_embed), dim=-1)\n single_io_embed = self.embed_merge(single_io_input)\n ctx_embed = self.agg_func(single_io_embed, scatter_idx)\n return None, None, ctx_embed\n\n\nclass BidirIOEmbed(AbstractIOEmbed):\n def __init__(self, args):\n super(BidirIOEmbed, self).__init__(args)\n self.vocab = {'unk': 0, 'eos': 1}\n for i, c in enumerate(STR_VOCAB):\n self.vocab[c] = i + 2\n self.tok_embed = nn.Embedding(len(self.vocab), args.embed_dim)\n self.lstm = nn.LSTM(args.embed_dim, args.embed_dim, 3, bidirectional=False)\n self.embed_merge = MLP(args.embed_dim * 2, [args.embed_dim], nonlinearity=args.act_func)\n self.device = args.device\n\n def io2idx_func(self, x):\n return [self.vocab[c] for c in x] + [self.vocab['eos']]\n\n def _pad_io(self, int_seqs):\n int_seqs = [torch.LongTensor(x) for x in int_seqs]\n lengths = [v.size(0) for v in int_seqs]\n return pad_sequence(int_seqs), lengths\n\n def padded_inputs(self, int_seqs):\n return self._pad_io(int_seqs)\n\n def padded_outputs(self, int_seqs):\n return self._pad_io(int_seqs)\n\n def embed_seq(self, packed_seq, scatter_idx):\n tok_embed = self.tok_embed(packed_seq.data)\n packed_input = PackedSequence(data=tok_embed, batch_sizes=packed_seq.batch_sizes,\n sorted_indices=packed_seq.sorted_indices, unsorted_indices=packed_seq.unsorted_indices)\n\n _, (h, c) = self.lstm(packed_input)\n return self.agg_func(h[-1], scatter_idx)\n\n def forward(self, inputs_list, outputs_list, cooked_data=None):\n if cooked_data is None:\n padded_i, padded_o, scatter_idx = self.cook_raw_io(inputs_list, outputs_list)\n else:\n padded_i, padded_o, scatter_idx = cooked_data.get_ios()\n scatter_idx = scatter_idx.to(self.device)\n packed_i = pack_padded_sequence(padded_i[0].to(self.device), padded_i[1], enforce_sorted=False)\n packed_o = pack_padded_sequence(padded_o[0].to(self.device), padded_o[1], enforce_sorted=False)\n\n input_embed = self.embed_seq(packed_i, scatter_idx)\n output_embed = self.embed_seq(packed_o, scatter_idx)\n merged = self.embed_merge(torch.cat((input_embed, output_embed), dim=-1))\n\n return input_embed, output_embed, merged\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# python3\n\"\"\"EBM definition and training logic.\"\"\"\nimport math\nimport os\nimport time\n\nfrom absl import app\nfrom absl import flags\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\n\n# pylint: disable=g-import-not-at-top\nUSE_LOCAL_FUN_MC = True\n\nif USE_LOCAL_FUN_MC:\n from fun_mc import using_tensorflow as fun_mc # pylint: disable=reimported\n\nfrom neutra.ebm import ebm_util\n# pylint: enable=g-import-not-at-top\n\n\nFLAGS = flags.FLAGS\ntfd = tfp.distributions\ntfb = tfp.bijectors\n\nflags.DEFINE_string('logdir', None, 'Directory to place all the artifacts in.')\n\nflags.DEFINE_integer('seed', 1, 'PRNG seed.')\n\nflags.DEFINE_enum('dataset', 'celeba', ['celeba', 'mnist'],\n 'Dataset to train on.')\n\nflags.DEFINE_integer('batch_size', 64, 'Training minibatch size.')\nflags.DEFINE_integer('train_steps', int(1e5),\n 'Total number of training iterations')\nflags.DEFINE_integer('save_steps', 1000, 'How often to save checkpoints.')\n\nflags.DEFINE_boolean('use_mcmc', False,\n 'Whether to use MCMC when training EBM.')\nflags.DEFINE_integer('mcmc_num_steps', 10, 'How many MCMC steps to take.')\nflags.DEFINE_float('mcmc_step_size', 0.1, 'MCMC initial step size.')\nflags.DEFINE_integer('mcmc_leapfrog_steps', 3, 'MCMC number of leapfrog steps.')\nflags.DEFINE_boolean('mcmc_adapt_step_size', True,\n 'Whether to adapt the step size.')\nflags.DEFINE_float('mcmc_momentum_stddev', 0.1, 'Initial momentum stddev.')\n\nflags.DEFINE_enum('p_loss', 'neutra_iid', ['neutra_hmc', 'neutra_iid'],\n 'What loss to use to train the EBM.')\nflags.DEFINE_float('p_learning_rate', 1e-4, 'EBM learning rate.')\nflags.DEFINE_float('p_adam_beta_1', 0.5, 'EBM ADAM beta_1.')\nflags.DEFINE_float('p_prior_weight', 0.01,\n 'Strength of the EBM quadratic prior.')\nflags.DEFINE_float('p_temperature', 1.0, 'EBM temperature.')\nflags.DEFINE_string('p_activation', 'relu', 'EBM activation function.')\nflags.DEFINE_float('p_center_regularizer', 0.0,\n 'Regularizer to center the EBM energy around 0.')\n\nflags.DEFINE_string('q_type', 'mean_field_gaussian', 'What Q to use.')\nflags.DEFINE_enum('q_loss', 'reverse_kl_mle',\n ['reverse_kl', 'forward_kl', 'reverse_kl_mle', 'mle'],\n 'What loss to use to train the flow model.')\nflags.DEFINE_float('q_learning_rate', 1e-4, 'Q learning rate.')\nflags.DEFINE_float('q_temperature', 1.0, 'Q temperature when sampling.')\nflags.DEFINE_integer(\n 'q_sub_steps', 1, 'Number of Q updates per training step. '\n 'Only applicable to reverse_kl_mle loss.')\nflags.DEFINE_float('q_entropy_weight', 1.0,\n 'Entropy coefficient for reverse KL losses.')\nflags.DEFINE_float('q_mle_coefficient', 1.0,\n 'MLE coefficient for the reverse_kl_mle loss.')\nflags.DEFINE_float('q_rkl_weight', 0.01,\n 'Q reverse KL coefficient for reverse_kl_mle loss')\n\nflags.DEFINE_integer('plot_steps', 500, 'How often to generate plots.')\n\n\nN_CH = 3 # Number of channels\nN_WH = 32 # Width of the images.\n\ntfk = tf.keras\ntfkl = tfk.layers\n\n\nclass EbmConv(tf.keras.Model):\n \"\"\"A convolutional EBM.\"\"\"\n\n def __init__(self, activation=tf.nn.relu, anchor_size=32):\n \"\"\"Initializes the network.\n\n Args:\n activation: What activation to use for the conv layers.\n anchor_size: A base size to use for the filter channels, setting the\n overall depth of the network.\n \"\"\"\n super(EbmConv, self).__init__()\n sn = ebm_util.SpectralNormalization\n self.net = tf.keras.Sequential([\n sn(\n tfkl.Conv2D(\n filters=anchor_size,\n kernel_size=3,\n strides=(1, 1),\n padding='SAME',\n activation=activation,\n input_shape=[N_WH, N_WH, N_CH])),\n sn(\n tfkl.Conv2D(\n filters=anchor_size * 2,\n kernel_size=4,\n strides=(2, 2),\n padding='SAME',\n activation=activation)),\n sn(\n tfkl.Conv2D(\n filters=anchor_size * 4,\n kernel_size=4,\n strides=(2, 2),\n padding='SAME',\n activation=activation)),\n sn(\n tfkl.Conv2D(\n filters=anchor_size * 4,\n kernel_size=4,\n strides=(2, 2),\n padding='SAME',\n activation=activation)),\n sn(tfkl.Conv2D(filters=1, kernel_size=4, strides=(1, 1))),\n ])\n\n def call(self, x):\n x = tf.reshape(x, shape=[-1, N_WH, N_WH, N_CH])\n prior = tf.reduce_sum((x**2), axis=[1, 2, 3])\n energy = tf.squeeze(self.net(x))\n return FLAGS.p_prior_weight * prior + energy / FLAGS.p_temperature\n\n\ndef make_u():\n \"\"\"Create an energy function.\"\"\"\n activation = {'relu': tf.nn.relu, 'lipswish': ebm_util.lipswish}\n u = EbmConv(activation=activation[FLAGS.p_activation])\n return u\n\n\nclass MeanFieldGaussianQ(tf.Module):\n \"\"\"A mean-field Gaussian Q.\"\"\"\n\n def __init__(self):\n super(MeanFieldGaussianQ, self).__init__()\n image_shape = [N_WH, N_WH, N_CH]\n ndims = np.prod(image_shape)\n zeros = tf.zeros(ndims)\n ones = tf.ones(ndims)\n self._base = tfd.Independent(tfd.Normal(zeros, ones), 1)\n b = tfb.ScaleMatvecDiag(\n scale_diag=tfp.util.TransformedVariable(ones, tfb.Softplus()))\n b = tfb.Shift(shift=tf.Variable(zeros))(b)\n b = tfb.Reshape(image_shape)(b)\n self._bijector = b\n\n def forward(self, x):\n \"\"\"Encodes a datapoint into the latent vector.\"\"\"\n return (self._bijector.inverse(x),\n self._bijector.inverse_log_det_jacobian(x, event_ndims=3))\n\n def reverse(self, z):\n \"\"\"Decodes a latent vector into the data space.\"\"\"\n return (self._bijector.forward(z),\n self._bijector.forward_log_det_jacobian(z, event_ndims=1))\n\n def log_prob(self, x):\n return self._bijector(self._base).log_prob(x)\n\n def sample_with_log_prob(self, n, temp=1.0):\n # TODO(siege): How to incorporate temperature here?\n z = self._base.sample(n)\n x = self._bijector.forward(z)\n fldj = self._bijector.forward_log_det_jacobian(z, event_ndims=1)\n return z, x, fldj + self._base.log_prob(z)\n\n\[email protected](autograph=False)\ndef train_q_fwd_kl(q, x, opt_q):\n \"\"\"KL[P || Q].\n\n Args:\n q: `ModelQ`.\n x: A batch of positive examples.\n opt_q: A `tf.optimizer.Optimizer`.\n\n Returns:\n loss: The mean loss across the batch.\n \"\"\"\n with tf.GradientTape() as tape:\n tape.watch(q.trainable_variables)\n loss = -tf.reduce_mean(q.log_prob(x))\n\n variables = tape.watched_variables()\n grads = tape.gradient(loss, variables)\n grads_and_vars = list(zip(grads, variables))\n opt_q.apply_gradients(grads_and_vars)\n return loss\n\n\ndef q_rev_kl(q, u):\n \"\"\"KL[Q || U].\n\n Args:\n q: `ModelQ`.\n u: A callable representing the energy function.\n\n Returns:\n loss: The mean loss across the batch.\n entropy: Entropy estimate of the `q` model.\n new_e_q: Mean energy of the negative samples sampled from `q`.\n \"\"\"\n _, x, log_p = q.sample_with_log_prob(\n FLAGS.batch_size, temp=FLAGS.q_temperature)\n\n # TODO(nijkamp): Is this normalization correct?\n n_pixel = N_WH * N_WH * N_CH\n entropy = tf.reduce_mean(-log_p / (math.log(2) * n_pixel))\n neg_e_q = tf.reduce_mean(u(x))\n\n return neg_e_q - FLAGS.q_entropy_weight * entropy, entropy, neg_e_q\n\n\[email protected](autograph=False)\ndef train_q_rev_kl(q, u, opt_q):\n \"\"\"KL[Q || U].\n\n Args:\n q: `ModelQ`.\n u: A callable representing the energy function.\n opt_q: A `tf.optimizer.Optimizer`.\n\n Returns:\n loss: The mean loss across the batch.\n entropy: Entropy estimate of the `q` model.\n \"\"\"\n with tf.GradientTape() as tape:\n tape.watch(q.trainable_variables)\n loss, entropy, _ = q_rev_kl(q, u)\n\n variables = q.trainable_variables\n grads = tape.gradient(loss, variables)\n grads_and_vars = list(zip(grads, variables))\n opt_q.apply_gradients(grads_and_vars)\n return loss, entropy\n\n\[email protected](autograph=False)\ndef train_q_rev_kl_mle(q, u, x_pos, alpha, opt_q):\n \"\"\"alpha KL[Q || U] + beta KL[data || Q].\n\n Args:\n q: `ModelQ`.\n u: A callable representing the energy function.\n x_pos: A batch of positive examples.\n alpha: Factor for the RKL term.\n opt_q: A `tf.optimizer.Optimizer`.\n\n Returns:\n loss: The mean overall loss across the batch.\n entropy: Entropy estimate of the `q` model.\n new_e_q: Mean energy of the negative samples sampled from `q`.\n mle_loss: Mean ML loss across the batch.\n grads_ebm_norm: Global norm of gradients for the RKL term.\n grads_mle_norm: Global norm of gradients for the MLE term.\n \"\"\"\n with tf.GradientTape() as tape1:\n tape1.watch(q.trainable_variables)\n ebm_loss, entropy, neg_e_q = q_rev_kl(q, u)\n ebm_loss = alpha * ebm_loss\n\n with tf.GradientTape() as tape2:\n tape2.watch(q.trainable_variables)\n mle_loss = FLAGS.q_mle_coefficient * tf.reduce_mean(\n -q.log_prob(x_pos) /\n (np.log(2.) * int(x_pos.get_shape()[1]) * int(x_pos.get_shape()[2]) *\n int(x_pos.get_shape()[3]))) # bits per subpixel\n\n loss = ebm_loss + mle_loss\n\n variables = q.trainable_variables\n\n grads_ebm = tape1.gradient(ebm_loss, variables)\n grads_mle = tape2.gradient(mle_loss, variables)\n\n grads_ebm_norm = tf.norm(\n tf.concat([tf.reshape(t, [-1]) for t in grads_ebm], axis=0))\n grads_mle_norm = tf.norm(\n tf.concat([tf.reshape(t, [-1]) for t in grads_mle], axis=0))\n\n grads_and_vars = list(zip(grads_ebm, variables))\n opt_q.apply_gradients(grads_and_vars)\n\n grads_and_vars = list(zip(grads_mle, variables))\n opt_q.apply_gradients(grads_and_vars)\n\n return loss, entropy, neg_e_q, mle_loss, grads_ebm_norm, grads_mle_norm\n\n\[email protected](autograph=False)\ndef train_q_mle(q, x_pos, opt_q):\n \"\"\"KL[data || Q].\n\n Args:\n q: `ModelQ`.\n x_pos: A batch of positive examples.\n opt_q: A `tf.optimizer.Optimizer`.\n\n Returns:\n loss: The mean overall loss across the batch.\n \"\"\"\n with tf.GradientTape() as tape:\n tape.watch(q.trainable_variables)\n\n mle_loss = tf.reduce_mean(\n -q.log_prob(x_pos) /\n (np.log(2.) * int(x_pos.get_shape()[1]) * int(x_pos.get_shape()[2]) *\n int(x_pos.get_shape()[3]))) # bits per subpixel\n\n # variables = tape.watched_variables()\n # assert len(variables) == len(q.trainable_variables)\n variables = q.trainable_variables\n grads = tape.gradient(mle_loss, variables)\n grads_and_vars = list(zip(grads, variables))\n opt_q.apply_gradients(grads_and_vars)\n return mle_loss\n\n\[email protected](autograph=False)\ndef train_p(q, u, x_pos, step_size, opt_p):\n \"\"\"Train P using the standard CD objective.\n\n Args:\n q: `ModelQ`.\n u: A callable representing the energy function.\n x_pos: A batch of positive examples.\n step_size: Step size to use for HMC.\n opt_p: A `tf.optimizer.Optimizer`.\n\n Returns:\n x_neg_q: Negative samples sampled from `q`.\n x_neg_p: Negative samples used to train `p`, possibly generated via HMC.\n p_accept: Acceptance rate of HMC.\n step_size: The new step size, possibly adapted to adjust the acceptance\n rate.\n pos_e: Mean energy of the positive samples across the batch.\n pos_e: Mean energy of the positive samples across the batch, after the\n parameter update.\n neg_e_q: Mean energy of `x_neg_q` across the batch.\n neg_e_p: Mean energy of `x_neg_p` across the batch.\n neg_e_p_updated: Mean energy of `x_neg_p` across the batch, after the\n parameter update.\n \"\"\"\n\n def create_momentum_sample_fn(state):\n sample_fn = lambda seed: tf.random.normal( # pylint: disable=g-long-lambda\n tf.shape(state),\n stddev=FLAGS.mcmc_momentum_stddev)\n return sample_fn\n\n _, x_neg_q, _ = q.sample_with_log_prob(\n FLAGS.batch_size, temp=FLAGS.q_temperature)\n neg_e_q = tf.reduce_mean(u(x_neg_q))\n\n def p_log_prob(x):\n return -u(x)\n\n if FLAGS.use_mcmc:\n\n def log_prob_non_transformed(x):\n p_log_p = p_log_prob(x)\n\n return p_log_p, (x,)\n\n # TODO(siege): Why aren't we actually using NeuTra?\n # def log_prob_transformed(z):\n # x, logdet = q.reverse(z)\n # p_log_p = p_log_prob(x)\n\n # return p_log_p + logdet, (x,)\n\n def kernel(hmc_state, step_size, step):\n \"\"\"HMC kernel.\"\"\"\n hmc_state, hmc_extra = fun_mc.hamiltonian_monte_carlo_step(\n hmc_state,\n step_size=step_size,\n num_integrator_steps=FLAGS.mcmc_leapfrog_steps,\n momentum_sample_fn=create_momentum_sample_fn(hmc_state.state),\n target_log_prob_fn=log_prob_non_transformed)\n\n mean_p_accept = tf.reduce_mean(\n tf.exp(tf.minimum(0., hmc_extra.log_accept_ratio)))\n\n if FLAGS.mcmc_adapt_step_size:\n step_size = fun_mc.sign_adaptation(\n step_size, output=mean_p_accept, set_point=0.9)\n\n return (hmc_state, step_size, step + 1), hmc_extra\n\n hmc_state, is_accepted = fun_mc.trace(\n state=(fun_mc.hamiltonian_monte_carlo_init(x_neg_q,\n log_prob_non_transformed),\n step_size, 0),\n fn=kernel,\n num_steps=FLAGS.mcmc_num_steps,\n trace_fn=lambda _, hmc_extra: hmc_extra.is_accepted)\n\n x_neg_p = hmc_state[0].state_extra[0]\n step_size = hmc_state[1]\n\n p_accept = tf.reduce_mean(tf.cast(is_accepted, tf.float32))\n else:\n x_neg_p = x_neg_q\n p_accept = 0.0\n step_size = 0.0\n\n with tf.GradientTape() as tape:\n tape.watch(u.trainable_variables)\n pos_e = tf.reduce_mean(u(x_pos))\n neg_e_p = tf.reduce_mean(u(x_neg_p))\n loss = pos_e - neg_e_p + tf.square(pos_e) * FLAGS.p_center_regularizer\n\n variables = u.trainable_variables\n grads = tape.gradient(loss, variables)\n grads_and_vars = list(zip(grads, variables))\n opt_p.apply_gradients(grads_and_vars)\n\n pos_e_updated = tf.reduce_mean(u(x_pos))\n neg_e_p_updated = tf.reduce_mean(u(x_neg_p))\n\n return (x_neg_q, x_neg_p, p_accept, step_size, pos_e, pos_e_updated, neg_e_q,\n neg_e_p, neg_e_p_updated)\n\n\[email protected](autograph=False)\ndef train_p_mh(q, u, x_pos, step_size, opt_p):\n \"\"\"Train P using a CD objective with negatives generated via IID MH step.\n\n Args:\n q: `ModelQ`.\n u: A callable representing the energy function.\n x_pos: A batch of positive examples.\n step_size: Step size to use for HMC.\n opt_p: A `tf.optimizer.Optimizer`.\n\n Returns:\n x_neg_q: Negative samples sampled from `q`.\n x_neg_p: Negative samples used to train `p`, possibly generated via HMC.\n p_accept: Acceptance rate of HMC.\n step_size: The new step size, possibly adapted to adjust the acceptance\n rate.\n pos_e: Mean energy of the positive samples across the batch.\n pos_e: Mean energy of the positive samples across the batch, after the\n parameter update.\n neg_e_q: Mean energy of `x_neg_q` across the batch.\n neg_e_p: Mean energy of `x_neg_p` across the batch.\n neg_e_p_updated: Mean energy of `x_neg_p` across the batch, after the\n parameter update.\n \"\"\"\n\n # (1) nt-iid q\n\n n = x_pos.shape[0]\n\n def p_log_prob(x):\n return -u(x)\n\n _, x1, g_x_1 = q.sample_with_log_prob(n=n, temp=1.0)\n _, x2, g_x_2 = q.sample_with_log_prob(n=n, temp=1.0)\n p_x_1 = p_log_prob(x1)\n p_x_2 = p_log_prob(x2)\n\n log_accept_ratio = p_x_2 - p_x_1 + g_x_1 - g_x_2\n log_accept_ratio_min = tf.math.minimum(\n tf.zeros_like(log_accept_ratio), log_accept_ratio)\n log_uniform = tf.math.log(\n tf.random.uniform(\n shape=tf.shape(log_accept_ratio), dtype=log_accept_ratio.dtype))\n\n is_accepted = log_uniform < log_accept_ratio_min\n\n def _expand_is_accepted_like(x):\n \"\"\"Helper to expand `is_accepted` like the shape of some input arg.\"\"\"\n with tf.name_scope('expand_is_accepted_like'):\n if x.shape is not None and is_accepted.shape is not None:\n expand_shape = list(is_accepted.shape) + [1] * (\n len(x.shape) - len(is_accepted.shape))\n else:\n expand_shape = tf.concat([\n tf.shape(is_accepted),\n tf.ones([tf.rank(x) - tf.rank(is_accepted)], dtype=tf.int32),\n ],\n axis=0)\n return tf.reshape(is_accepted, expand_shape)\n\n x = tf.where(_expand_is_accepted_like(x1), x2, x1)\n\n # (2) update p\n\n neg_e_q = tf.reduce_mean(u(x1))\n\n x_neg_q = x1\n x_neg_p = x\n p_accept = tf.reduce_mean(tf.cast(is_accepted, tf.float32))\n step_size = 0.0\n\n with tf.GradientTape() as tape:\n tape.watch(u.trainable_variables)\n pos_e = tf.reduce_mean(u(x_pos))\n neg_e_p = tf.reduce_mean(u(x_neg_p))\n loss = pos_e - neg_e_p + tf.square(pos_e) * FLAGS.p_center_regularizer\n\n # variables = tape.watched_variables()\n variables = u.trainable_variables\n grads = tape.gradient(loss, variables)\n grads_and_vars = list(zip(grads, variables))\n opt_p.apply_gradients(grads_and_vars)\n\n pos_e_updated = tf.reduce_mean(u(x_pos))\n neg_e_p_updated = tf.reduce_mean(u(x_neg_p))\n\n return (x_neg_q, x_neg_p, p_accept, step_size, pos_e, pos_e_updated, neg_e_q,\n neg_e_p, neg_e_p_updated)\n\n\ndef main(unused_args):\n del unused_args\n\n #\n # General setup.\n #\n\n ebm_util.init_tf2()\n\n ebm_util.set_seed(FLAGS.seed)\n\n output_dir = FLAGS.logdir\n checkpoint_dir = os.path.join(output_dir, 'checkpoint')\n samples_dir = os.path.join(output_dir, 'samples')\n\n tf.io.gfile.makedirs(samples_dir)\n tf.io.gfile.makedirs(checkpoint_dir)\n\n log_f = tf.io.gfile.GFile(os.path.join(output_dir, 'log.out'), mode='w')\n logger = ebm_util.setup_logging('main', log_f, console=False)\n logger.info({k: v._value for (k, v) in FLAGS._flags().items()}) # pylint: disable=protected-access\n\n #\n # Data\n #\n\n if FLAGS.dataset == 'mnist':\n x_train = ebm_util.mnist_dataset(N_CH)\n elif FLAGS.dataset == 'celeba':\n x_train = ebm_util.celeba_dataset()\n else:\n raise ValueError(f'Unknown dataset. {FLAGS.dataset}')\n train_ds = tf.data.Dataset.from_tensor_slices(x_train).shuffle(10000).batch(\n FLAGS.batch_size)\n\n #\n # Models\n #\n\n if FLAGS.q_type == 'mean_field_gaussian':\n q = MeanFieldGaussianQ()\n u = make_u()\n\n #\n # Optimizers\n #\n\n def lr_p(step):\n lr = FLAGS.p_learning_rate * (1. - (step / (1.5 * FLAGS.train_steps)))\n return lr\n\n def lr_q(step):\n lr = FLAGS.q_learning_rate * (1. - (step / (1.5 * FLAGS.train_steps)))\n return lr\n\n opt_q = tf.optimizers.Adam(learning_rate=ebm_util.LambdaLr(lr_q))\n opt_p = tf.optimizers.Adam(\n learning_rate=ebm_util.LambdaLr(lr_p), beta_1=FLAGS.p_adam_beta_1)\n\n #\n # Checkpointing\n #\n\n global_step_var = tf.Variable(0, trainable=False)\n checkpoint = tf.train.Checkpoint(\n opt_p=opt_p, opt_q=opt_q, u=u, q=q, global_step_var=global_step_var)\n\n checkpoint_path = os.path.join(checkpoint_dir, 'checkpoint')\n if tf.io.gfile.exists(checkpoint_path + '.index'):\n print(f'Restoring from {checkpoint_path}')\n checkpoint.restore(checkpoint_path)\n\n #\n # Stats initialization\n #\n\n stat_i = []\n stat_keys = [\n 'E_pos', # Mean energy of the positive samples.\n 'E_neg_q', # Mean energy of the negative samples (pre-HMC).\n 'E_neg_p', # Mean energy of the negative samples (post-HMC).\n 'H', # Entropy of Q (if known).\n 'pd_pos', # Pairse differences of the positive samples.\n 'pd_neg_q', # Pairwise differences of the negative samples (pre-HMC).\n 'pd_neg_p', # Pairwise differences of the negative samples (post-HMC).\n 'hmc_disp', # L2 distance between initial and final entropyMC samples.\n 'hmc_p_accept', # entropyMC P(accept).\n 'hmc_step_size', # entropyMC step size.\n 'x_neg_p_min', # Minimum value of the negative samples (post-HMC).\n 'x_neg_p_max', # Maximum value of the negative samples (post-HMC).\n 'time', # Time taken to do the training step.\n ]\n stat = {k: [] for k in stat_keys}\n\n def array_to_str(a, fmt='{:>8.4f}'):\n return ' '.join([fmt.format(v) for v in a])\n\n def stats_callback(step, entropy, pd_neg_q):\n del step, entropy, pd_neg_q\n\n\n step_size = FLAGS.mcmc_step_size\n\n train_ds_iter = iter(train_ds)\n x_pos_1 = ebm_util.data_preprocess(next(train_ds_iter))\n x_pos_2 = ebm_util.data_preprocess(next(train_ds_iter))\n\n global_step = global_step_var.numpy()\n\n while global_step < (FLAGS.train_steps + 1):\n for x_pos in train_ds:\n\n # Drop partial batches.\n if x_pos.shape[0] != FLAGS.batch_size:\n continue\n\n #\n # Update\n #\n\n start_time = time.time()\n\n x_pos = ebm_util.data_preprocess(x_pos)\n x_pos = ebm_util.data_discrete_noise(x_pos)\n\n if FLAGS.p_loss == 'neutra_hmc':\n (x_neg_q, x_neg_p, p_accept, step_size, pos_e, pos_e_updated, neg_e_q,\n neg_e_p, neg_e_p_updated) = train_p(q, u, x_pos, step_size, opt_p)\n elif FLAGS.p_loss == 'neutra_iid':\n (x_neg_q, x_neg_p, p_accept, step_size, pos_e, pos_e_updated, neg_e_q,\n neg_e_p, neg_e_p_updated) = train_p_mh(q, u, x_pos, step_size, opt_p)\n else:\n raise ValueError(f'Unknown P loss {FLAGS.p_loss}')\n\n if FLAGS.q_loss == 'forward_kl':\n train_q_fwd_kl(q, x_neg_p, opt_q)\n entropy = 0.0\n mle_loss = 0.0\n elif FLAGS.q_loss == 'reverse_kl':\n for _ in range(10):\n _, entropy = train_q_rev_kl(q, u, opt_q)\n mle_loss = 0.0\n elif FLAGS.q_loss == 'reverse_kl_mle':\n for _ in range(FLAGS.q_sub_steps):\n alpha = FLAGS.q_rkl_weight\n (_, entropy, _, mle_loss, norm_grads_ebm,\n norm_grads_mle) = train_q_rev_kl_mle(q, u, x_pos,\n tf.convert_to_tensor(alpha),\n opt_q)\n\n elif FLAGS.q_loss == 'mle':\n mle_loss = train_q_mle(q, x_pos, opt_q)\n entropy = 0.0\n else:\n raise ValueError(f'Unknown Q loss {FLAGS.q_loss}')\n\n end_time = time.time()\n\n #\n # Stats\n #\n\n hmc_disp = tf.reduce_mean(\n tf.norm(\n tf.reshape(x_neg_q, [64, -1]) - tf.reshape(x_neg_p, [64, -1]),\n axis=1))\n\n if global_step % FLAGS.plot_steps == 0:\n\n # Positives + negatives.\n ebm_util.plot(\n tf.reshape(\n ebm_util.data_postprocess(x_neg_q),\n [FLAGS.batch_size, N_WH, N_WH, N_CH]),\n os.path.join(samples_dir, f'x_neg_q_{global_step}.png'))\n ebm_util.plot(\n tf.reshape(\n ebm_util.data_postprocess(x_neg_p),\n [FLAGS.batch_size, N_WH, N_WH, N_CH]),\n os.path.join(samples_dir, f'x_neg_p_{global_step}.png'))\n ebm_util.plot(\n tf.reshape(\n ebm_util.data_postprocess(x_pos),\n [FLAGS.batch_size, N_WH, N_WH, N_CH]),\n os.path.join(samples_dir, f'x_pos_{global_step}.png'))\n\n # Samples for various temperatures.\n for t in [0.1, 0.5, 1.0, 2.0, 4.0]:\n _, x_neg_q_t, _ = q.sample_with_log_prob(FLAGS.batch_size, temp=t)\n ebm_util.plot(\n tf.reshape(\n ebm_util.data_postprocess(x_neg_q_t),\n [FLAGS.batch_size, N_WH, N_WH, N_CH]),\n os.path.join(samples_dir, f'x_neg_t_{t}_{global_step}.png'))\n\n stats_callback(global_step, entropy,\n ebm_util.nearby_difference(x_neg_q))\n\n stat_i.append(global_step)\n stat['E_pos'].append(pos_e_updated)\n stat['E_neg_q'].append(neg_e_q)\n stat['E_neg_p'].append(neg_e_p)\n stat['H'].append(entropy)\n stat['pd_neg_q'].append(ebm_util.nearby_difference(x_neg_q))\n stat['pd_neg_p'].append(ebm_util.nearby_difference(x_neg_p))\n stat['pd_pos'].append(ebm_util.nearby_difference(x_pos))\n stat['hmc_disp'].append(hmc_disp)\n stat['hmc_p_accept'].append(p_accept)\n stat['hmc_step_size'].append(step_size)\n stat['x_neg_p_min'].append(tf.reduce_min(x_neg_p))\n stat['x_neg_p_max'].append(tf.reduce_max(x_neg_p))\n stat['time'].append(end_time - start_time)\n\n ebm_util.plot_stat(stat_keys, stat, stat_i, output_dir)\n\n # Doing a linear interpolation in the latent space.\n z_pos_1 = q.forward(x_pos_1)[0]\n z_pos_2 = q.forward(x_pos_2)[0]\n\n x_alphas = []\n n_steps = 10\n for j in range(0, n_steps + 1):\n alpha = (j / n_steps)\n z_alpha = (1. - alpha) * z_pos_1 + (alpha) * z_pos_2\n x_alpha = q.reverse(z_alpha)[0]\n x_alphas.append(x_alpha)\n\n ebm_util.plot_n_by_m(\n ebm_util.data_postprocess(\n tf.reshape(\n tf.stack(x_alphas, axis=1),\n [(n_steps + 1) * FLAGS.batch_size, N_WH, N_WH, N_CH])),\n os.path.join(samples_dir, f'x_alpha_{global_step}.png'),\n FLAGS.batch_size, n_steps + 1)\n\n # Doing random perturbations in the latent space.\n for eps in [1e-4, 1e-3, 1e-2, 1e-1, 1e0, 2e0, 2.5e0, 3e0]:\n z_pos_2_eps = z_pos_2 + eps * tf.random.normal(z_pos_2.shape)\n x_alpha = q.reverse(z_pos_2_eps)[0]\n ebm_util.plot(\n tf.reshape(\n ebm_util.data_postprocess(x_alpha),\n [FLAGS.batch_size, N_WH, N_WH, N_CH]),\n os.path.join(samples_dir, f'x_alpha_eps_{eps}_{global_step}.png'))\n\n # Checking the log-probabilites of positive and negative examples under\n # Q.\n z_neg_test, x_neg_test, _ = q.sample_with_log_prob(\n FLAGS.batch_size, temp=FLAGS.q_temperature)\n z_pos_test = q.forward(x_pos)[0]\n\n z_neg_test_pd = ebm_util.nearby_difference(z_neg_test)\n z_pos_test_pd = ebm_util.nearby_difference(z_pos_test)\n\n z_norms_neg = tf.reduce_mean(tf.norm(z_neg_test, axis=1))\n z_norms_pos = tf.reduce_mean(tf.norm(z_pos_test, axis=1))\n\n log_prob_neg = tf.reduce_mean(q.log_prob(x_neg_test))\n log_prob_pos = tf.reduce_mean(q.log_prob(x_pos))\n\n logger.info(' '.join([\n f'i={global_step:6d}',\n # Pre-update, post-update\n (f'E_pos=[{pos_e:10.4f} {pos_e_updated:10.4f} ' +\n f'{pos_e_updated - pos_e:10.4f}]'),\n # Pre-update pre-HMC, pre-update post-HMC, post-update post-HMC\n (f'E_neg=[{neg_e_q:10.4f} {neg_e_p:10.4f} ' +\n f'{neg_e_p_updated:10.4f} {neg_e_p_updated - neg_e_p:10.4f}]'),\n f'mle={tf.reduce_mean(mle_loss):8.4f}',\n f'H={entropy:8.4f}',\n f'norm_grads_ebm={norm_grads_ebm:8.4f}',\n f'norm_grads_mle={norm_grads_mle:8.4f}',\n f'pd(x_pos)={ebm_util.nearby_difference(x_pos):8.4f}',\n f'pd(x_neg_q)={ebm_util.nearby_difference(x_neg_q):8.4f}',\n f'pd(x_neg_p)={ebm_util.nearby_difference(x_neg_p):8.4f}',\n f'hmc_disp={hmc_disp:8.4f}',\n f'p(accept)={p_accept:8.4f}',\n f'step_size={step_size:8.4f}',\n # Min, max.\n (f'x_neg_q=[{tf.reduce_min(x_neg_q):8.4f} ' +\n f'{tf.reduce_max(x_neg_q):8.4f}]'),\n (f'x_neg_p=[{tf.reduce_min(x_neg_p):8.4f} ' +\n f'{tf.reduce_max(x_neg_p):8.4f}]'),\n f'z_neg_norm={array_to_str(z_norms_neg)}',\n f'z_pos_norm={array_to_str(z_norms_pos)}',\n f'z_neg_test_pd={z_neg_test_pd:>8.2f}',\n f'z_pos_test_pd={z_pos_test_pd:>8.2f}',\n f'log_prob_neg={log_prob_neg:12.2f}',\n f'log_prob_pos={log_prob_pos:12.2f}',\n ]))\n\n if global_step % FLAGS.save_steps == 0:\n\n global_step_var.assign(global_step)\n checkpoint.write(os.path.join(checkpoint_dir, 'checkpoint'))\n\n global_step += 1\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('log_dir')\n app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Functions and classes related to optimization (weight updates).\"\"\"\n\nimport re\nimport six\nimport tensorflow.compat.v1 as tf\n\nfrom readtwice.models import lamb_optimizer\n\n\ndef create_optimizer(loss,\n init_lr,\n num_train_steps,\n num_warmup_steps,\n use_tpu,\n optimizer=\"adamw\",\n poly_power=1.0,\n start_warmup_step=0,\n learning_rate_schedule=\"poly_decay\",\n weight_decay_rate=0.01,\n reduce_loss_sum=False):\n \"\"\"Creates an optimizer training op.\"\"\"\n global_step = tf.train.get_or_create_global_step()\n\n learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)\n\n # Implements linear decay of the learning rate.\n if learning_rate_schedule == \"poly_decay\":\n learning_rate = tf.train.polynomial_decay(\n learning_rate,\n global_step,\n num_train_steps,\n end_learning_rate=0.0,\n power=poly_power,\n cycle=False)\n elif learning_rate_schedule == \"inverse_sqrt\":\n learning_rate = inverse_sqrt_learning_rate_schedule(\n learning_rate=learning_rate,\n step=global_step,\n warmup_steps=num_warmup_steps,\n offset=start_warmup_step)\n else:\n raise ValueError(\"Not supported learning_rate_schedule: \",\n learning_rate_schedule)\n\n # Implements linear warmup. I.e., if global_step - start_warmup_step <\n # num_warmup_steps, the learning rate will be\n # `(global_step - start_warmup_step)/num_warmup_steps * init_lr`.\n if num_warmup_steps:\n tf.logging.info(\"++++++ warmup starts at step \" + str(start_warmup_step) +\n \", for \" + str(num_warmup_steps) + \" steps ++++++\")\n global_steps_int = tf.cast(global_step, tf.int32)\n start_warm_int = tf.constant(start_warmup_step, dtype=tf.int32)\n global_steps_int = global_steps_int - start_warm_int\n warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32)\n\n global_steps_float = tf.cast(global_steps_int, tf.float32)\n warmup_steps_float = tf.cast(warmup_steps_int, tf.float32)\n\n warmup_percent_done = global_steps_float / warmup_steps_float\n warmup_learning_rate = init_lr * warmup_percent_done\n\n is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32)\n learning_rate = ((1.0 - is_warmup) * learning_rate +\n is_warmup * warmup_learning_rate)\n\n # It is OK that you use this optimizer for finetuning, since this\n # is how the model was trained (note that the Adam m/v variables are NOT\n # loaded from init_checkpoint.)\n # It is OK to use AdamW in the finetuning even the model is trained by LAMB.\n # As report in the Bert pulic github, the learning rate for SQuAD 1.1 finetune\n # is 3e-5, 4e-5 or 5e-5. For LAMB, the users can use 3e-4, 4e-4,or 5e-4 for a\n # batch size of 64 in the finetune.\n if optimizer == \"adamw\":\n tf.logging.info(\"using adamw\")\n optimizer = AdamWeightDecayOptimizer(\n learning_rate=learning_rate,\n weight_decay_rate=weight_decay_rate,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-6,\n exclude_from_weight_decay=[\"LayerNorm\", \"layer_norm\", \"bias\"])\n elif optimizer == \"lamb\":\n tf.logging.info(\"using lamb\")\n optimizer = lamb_optimizer.LAMBOptimizer(\n learning_rate=learning_rate,\n weight_decay_rate=weight_decay_rate,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-6,\n exclude_from_weight_decay=[\"LayerNorm\", \"layer_norm\", \"bias\"])\n else:\n raise ValueError(\"Not supported optimizer: \", optimizer)\n\n if use_tpu:\n if reduce_loss_sum:\n optimizer = tf.tpu.CrossShardOptimizer(\n optimizer, reduction=tf.losses.Reduction.SUM)\n else:\n optimizer = tf.tpu.CrossShardOptimizer(optimizer)\n\n tvars = tf.trainable_variables()\n grads = tf.gradients(loss, tvars)\n\n # This is how the model was pre-trained.\n (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0)\n\n train_op = optimizer.apply_gradients(\n list(zip(grads, tvars)), global_step=global_step)\n\n # Normally the global step update is done inside of `apply_gradients`.\n # However, neither `AdamWeightDecayOptimizer` nor `LAMBOptimizer` do this.\n # But if you use a different optimizer, you should probably take this line\n # out.\n new_global_step = global_step + 1\n train_op = tf.group(train_op, [global_step.assign(new_global_step)])\n return train_op\n\n\n# Adapted from `learning_rate_schedule_noam` in Mesh-TensorFlow.\ndef inverse_sqrt_learning_rate_schedule(learning_rate,\n step,\n warmup_steps=10000,\n offset=0):\n \"\"\"Inverse square root of time learning rate schedule with a flat warmup.\n\n learning_rate * (rsqrt(max(step_num, warmup_steps))\n / rsqrt(warmup_steps)\n\n Args:\n learning_rate: A tf.scalar representing the initial learning rate.\n step: A tf.scalar representing the step we want the learning rate for.\n warmup_steps: A number. Must not be negative.\n offset: A number used for finetuning. Starts the learning-rate decay\n schedule from this step forwards. Prior to this step, the learning rate is\n the same as if it were a warmup step.\n\n Returns:\n A tf.Scalar, the learning rate for the step.\n \"\"\"\n step_num = tf.cast(step, tf.float32) - offset\n warmup_steps = tf.maximum(tf.cast(warmup_steps, tf.float32), 1.0)\n return (learning_rate * tf.math.rsqrt(tf.maximum(step_num, warmup_steps)) /\n tf.math.rsqrt(warmup_steps))\n\n\nclass AdamWeightDecayOptimizer(tf.train.Optimizer):\n \"\"\"A basic Adam optimizer that includes \"correct\" L2 weight decay.\"\"\"\n\n def __init__(self,\n learning_rate,\n weight_decay_rate=0.0,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-6,\n exclude_from_weight_decay=None,\n name=\"AdamWeightDecayOptimizer\"):\n \"\"\"Constructs a AdamWeightDecayOptimizer.\"\"\"\n super(AdamWeightDecayOptimizer, self).__init__(False, name)\n\n self.learning_rate = learning_rate\n self.weight_decay_rate = weight_decay_rate\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.epsilon = epsilon\n self.exclude_from_weight_decay = exclude_from_weight_decay\n\n def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n \"\"\"See base class.\"\"\"\n assignments = []\n for (grad, param) in grads_and_vars:\n if grad is None or param is None:\n continue\n\n param_name = self._get_variable_name(param.name)\n\n m = tf.get_variable(\n name=six.ensure_str(param_name) + \"/adam_m\",\n shape=param.shape.as_list(),\n dtype=tf.float32,\n trainable=False,\n initializer=tf.zeros_initializer())\n v = tf.get_variable(\n name=six.ensure_str(param_name) + \"/adam_v\",\n shape=param.shape.as_list(),\n dtype=tf.float32,\n trainable=False,\n initializer=tf.zeros_initializer())\n\n # Standard Adam update.\n next_m = (\n tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))\n next_v = (\n tf.multiply(self.beta_2, v) +\n tf.multiply(1.0 - self.beta_2, tf.square(grad)))\n\n update = next_m / (tf.sqrt(next_v) + self.epsilon)\n\n # Just adding the square of the weights to the loss function is *not*\n # the correct way of using L2 regularization/weight decay with Adam,\n # since that will interact with the m and v parameters in strange ways.\n #\n # Instead we want ot decay the weights in a manner that doesn't interact\n # with the m/v parameters. This is equivalent to adding the square\n # of the weights to the loss with plain (non-momentum) SGD.\n if self._do_use_weight_decay(param_name):\n update += self.weight_decay_rate * param\n\n update_with_lr = self.learning_rate * update\n\n next_param = param - update_with_lr\n\n assignments.extend(\n [param.assign(next_param),\n m.assign(next_m),\n v.assign(next_v)])\n return tf.group(*assignments, name=name)\n\n def _do_use_weight_decay(self, param_name):\n \"\"\"Whether to use L2 weight decay for `param_name`.\"\"\"\n if not self.weight_decay_rate:\n return False\n if self.exclude_from_weight_decay:\n for r in self.exclude_from_weight_decay:\n if re.search(r, param_name) is not None:\n return False\n return True\n\n def _get_variable_name(self, param_name):\n \"\"\"Get the variable name from the tensor name.\"\"\"\n m = re.match(\"^(.*):\\\\d+$\", six.ensure_str(param_name))\n if m is not None:\n param_name = m.group(1)\n return param_name\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Group-wise Evaluation functions supporting Movielens examples.\n\"\"\"\n\nimport array\nimport collections\n\nfrom typing import Dict, List, Optional, Text, Tuple\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef evaluate_sparse_dataset(\n user_model,\n movie_model,\n test,\n movies,\n user_features,\n item_features,\n cutoffs,\n groups = None,\n train = None,\n):\n \"\"\"Evaluates a Movielens model on the supplied (SparseTensor) datasets.\n\n Args:\n user_model: User representation model.\n movie_model: Movie representation model.\n test: Test dataset, in batch format.\n movies: Dataset of movies.\n user_features: A list of user features (used by models consider user\n features).\n item_features: A list of item features (used by models consider item\n features).\n cutoffs: A list of cutoff values at which to compute precision and recall.\n groups: A list of strings for group-wise evaluations. Assume group is among\n input features now.\n train: Training dataset. If supplied, recommendations for training watches\n will be removed.\n\n Returns:\n Dictionary of metrics.\n \"\"\"\n\n # One batch data of `movies` contains all the candidates.\n for i in movies.take(1):\n movie_candidates = i\n movies = movie_candidates[\"item_id\"].values.numpy()\n\n movie_vocabulary = dict(zip(movies.tolist(), range(len(movies))))\n\n train_user_to_movie_ids = collections.defaultdict(lambda: array.array(\"i\"))\n test_user_to_movies_ids = collections.defaultdict(lambda: array.array(\"i\"))\n # map user ids to features\n test_user_to_features = collections.defaultdict(dict)\n # map item ids to features\n test_item_to_features = collections.defaultdict(dict)\n\n def tensor_to_numpy(tensor):\n if isinstance(tensor, tf.SparseTensor):\n tensor = tf.sparse.to_dense(tensor)\n return tensor.numpy().squeeze()\n\n if train is not None:\n for batch in train:\n users = tensor_to_numpy(batch[\"user_id\"])\n movies = tensor_to_numpy(batch[\"item_id\"])\n for user, movie in zip(users, movies):\n train_user_to_movie_ids[user].append(movie_vocabulary[movie])\n\n for batch in test:\n users = tensor_to_numpy(batch[\"user_id\"]) # shape (batch_size, 1)\n movies = tensor_to_numpy(batch[\"item_id\"])\n user_feature_dict = {\n feature: tensor_to_numpy(batch[feature]) for feature in user_features\n }\n item_features_dict = {\n feature: tensor_to_numpy(batch[feature]) for feature in item_features\n }\n for i, (user, movie) in enumerate(zip(users, movies)):\n item = movie_vocabulary[movie]\n test_user_to_movies_ids[user].append(item)\n\n if user not in test_user_to_features:\n test_user_to_features[user] = {\n k: [v[i]] for k, v in user_feature_dict.items()\n }\n if item not in test_item_to_features:\n test_item_to_features[item] = {\n k: [v[i]] for k, v in item_features_dict.items()\n }\n\n movie_embeddings = movie_model(movie_candidates).numpy()\n\n precision_values = collections.defaultdict(list)\n recall_values = collections.defaultdict(list)\n if groups is not None:\n groups_wise_precision_values = {}\n groups_wise_recall_values = {}\n for group in groups:\n groups_wise_precision_values[group] = collections.defaultdict(\n lambda: collections.defaultdict(list))\n groups_wise_recall_values[group] = collections.defaultdict(\n lambda: collections.defaultdict(list))\n\n for (user, test_movies) in test_user_to_movies_ids.items():\n user_embedding = user_model(test_user_to_features[user]).numpy()\n scores = (user_embedding @ movie_embeddings.T).flatten()\n test_movies = np.frombuffer(test_movies, dtype=np.int32)\n if train is not None:\n train_movies = np.frombuffer(\n train_user_to_movie_ids[user], dtype=np.int32)\n scores[train_movies] = -1e6\n\n top_ranks = np.argsort(-scores)\n for k in cutoffs:\n top_movies = top_ranks[:k]\n num_test_movies_in_k = sum(x in top_movies for x in test_movies)\n sample_precision = num_test_movies_in_k / k\n sample_recall = num_test_movies_in_k / len(test_movies)\n precision_values[k].append(sample_precision)\n recall_values[k].append(sample_recall)\n\n # Add group metrics.\n if groups is not None:\n for group in groups:\n if group.startswith(\"item:\"):\n # Parse item-side subgroup features.\n subgroups = []\n for movie in test_movies:\n subgroups.extend(\n test_item_to_features[movie][group.replace(\"item:\", \"\")])\n else:\n # Parse user-side subgroup features.\n subgroups = test_user_to_features[user][group]\n for subgroup in subgroups:\n groups_wise_precision_values[group][subgroup][k].append(\n sample_precision)\n groups_wise_recall_values[group][subgroup][k].append(sample_recall)\n\n # Logging for averaged performance.\n number_of_samples = len(precision_values[cutoffs[0]])\n precision_results = {\n f\"precision_at_{k}\": np.mean(precision_values[k]) for k in cutoffs\n }\n recall_results = {\n f\"recall_at_{k}\": np.mean(recall_values[k]) for k in cutoffs\n }\n print(f\"\\nAveraged (Num of samples):{number_of_samples}\")\n print(precision_results, \"\\n\", recall_results)\n\n # Logging for group-wise performance.\n if groups is not None:\n for group in groups:\n print(\"\\nGroup:\", group)\n target_group_precision = groups_wise_precision_values[group]\n target_group_recall = groups_wise_recall_values[group]\n for subgroup in sorted(list(target_group_precision.keys())):\n print(\n f\"Subgroup={subgroup}(Num of samples:{len(target_group_precision[subgroup][cutoffs[0]])}\"\n )\n print({\n f\"precision_at_{k}\": np.mean(target_group_precision[subgroup][k])\n for k in cutoffs\n })\n print({\n f\"recall_at_{k}\": np.mean(target_group_recall[subgroup][k])\n for k in cutoffs\n })\n\n return recall_results, precision_results\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Helper functions for searching symbolic forms of density functionals.\"\"\"\n\nimport time\n\nfrom absl import logging\nfrom jax.interpreters import xla\nimport numpy as np\n\nfrom symbolic_functionals.syfes.dataset import dataset\nfrom symbolic_functionals.syfes.symbolic import enhancement_factors\nfrom symbolic_functionals.syfes.symbolic import evaluators\nfrom symbolic_functionals.syfes.symbolic import mutators\nfrom symbolic_functionals.syfes.symbolic import xc_functionals\n\n\ndef make_mutator(instruction_pool,\n mutation_pool,\n max_num_instructions,\n max_num_bound_parameters,\n num_fixed_instructions,\n component_mutation_probabilities=None,\n seed=None):\n \"\"\"Constructs mutator for functional forms.\n\n Args:\n instruction_pool: Dict, the pool of possible instructions.\n mutation_pool: Dict, the pool of possible mutation rules.\n max_num_instructions: Integer, the maximum number of instructions.\n max_num_bound_parameters: Integer, the maximum number of bound parameters.\n num_fixed_instructions: Integer, the number of fixed instructions.\n component_mutation_probabilities: Sequence of 3 floats, the probabilities\n for mutating exchange, same-spin or opposite-spin component of the\n functional.\n seed: Integer, random seed.\n\n Returns:\n Instance of mutators.XCFunctionalMutator, the resulting mutator.\n \"\"\"\n return mutators.XCFunctionalMutator(\n mutator_x=mutators.EnhancementFactorMutator(\n instruction_pool=instruction_pool,\n mutation_pool=mutation_pool,\n max_num_instructions=max_num_instructions,\n num_fixed_instructions=num_fixed_instructions,\n max_num_bound_parameters=max_num_bound_parameters),\n mutator_css=mutators.EnhancementFactorMutator(\n instruction_pool=instruction_pool,\n mutation_pool=mutation_pool,\n max_num_instructions=max_num_instructions,\n num_fixed_instructions=num_fixed_instructions,\n max_num_bound_parameters=max_num_bound_parameters),\n mutator_cos=mutators.EnhancementFactorMutator(\n instruction_pool=instruction_pool,\n mutation_pool=mutation_pool,\n max_num_instructions=max_num_instructions,\n num_fixed_instructions=num_fixed_instructions,\n max_num_bound_parameters=max_num_bound_parameters),\n component_mutation_probabilities=component_mutation_probabilities,\n seed=seed)\n\n\ndef make_evaluators_with_mgcdb84_partitioning(\n dataset_directory,\n feature_names_x,\n feature_names_css,\n feature_names_cos,\n spin_singlet=False,\n targets='mgcdb84_ref',\n num_targets=None,\n omega=0.3,\n alpha=1.0,\n beta=-0.85,\n eval_modes=('jit', 'onp', 'onp')):\n \"\"\"Constructs evaluators based on mgcdb84 training and validation set.\n\n Args:\n dataset_directory: String, the directory to dataset.\n feature_names_x: List of strings, the features for exchange enhancement\n factor.\n feature_names_css: List of strings, the features for same-spin correlation\n enhancement factor.\n feature_names_cos: List of strings, the features for opposite-spin\n correlation enhancement factor.\n spin_singlet: Boolean, if True, only spin unpolarized molecules will\n be included in dataset.\n targets: String, the targets used for evaluating WRMSD. Defaults to\n 'mgcdb84_ref', which computes target values from reference values given\n by MCGDB84. Other supported values are:\n * B97X: target values are exchange-correlation energies evaluated by\n B97 exchange functional.\n * B97: target values are exchange-correlation energies evaluated by\n B97 functional.\n num_targets: Integer, the number of targets used to construct train\n or validation evaluator. Defaults to use all targets in MGCDB84 training\n set and all targets in validation set.\n omega: Float, RSH parameter for functional used in SCF calculations.\n alpha: Float, RSH parameter for functional used in SCF calculations.\n beta: Float, RSH parameter for functional used in SCF calculations.\n Default values of omega, alpha, beta are those of wB97M-V functional\n obtained with pyscf.dft.libxc.rsh_coeff('wb97m_v')\n eval_modes: Sequence of 3 strings, evaluation mode for training, validation\n and test evaluators. Possible values are onp, jnp and jit.\n\n Returns:\n List of 3 instances of evaluators.Evaluator, the evaluator for training,\n validation and test losses.\n \"\"\"\n evaluator_list = []\n for paritition_index, partition in enumerate(['train', 'validation', 'test']):\n evaluator = evaluators.Evaluator.from_dataset(\n subset=dataset.Dataset.load_mcgdb84_subset(\n dataset_directory=dataset_directory,\n mgcdb84_set=partition,\n spin_singlet=spin_singlet,\n nrow_property=num_targets),\n feature_names_x=feature_names_x,\n feature_names_css=feature_names_css,\n feature_names_cos=feature_names_cos,\n targets=targets,\n omega=omega,\n alpha=alpha,\n beta=beta,\n eval_mode=eval_modes[paritition_index])\n logging.info('Evaluator on %s set constructed: %s', partition, evaluator)\n evaluator_list.append(evaluator)\n\n return evaluator_list\n\n\ndef make_evaluators_with_mgcdb84_type(\n dataset_directory,\n mcgdb84_types,\n feature_names_x,\n feature_names_css,\n feature_names_cos,\n train_validation_test_split=(0.6, 0.2, 0.2),\n spin_singlet=False,\n targets='mgcdb84_ref',\n num_targets=None,\n omega=0.3,\n alpha=1.0,\n beta=-0.85,\n eval_modes=('jit', 'onp', 'onp')):\n \"\"\"Constructs evaluators using given type of MGCDB84.\n\n Data in given type will be combined and split into training, validation\n and test sets, resulting in 3 evaluators.\n\n Args:\n dataset_directory: String, the directory to dataset.\n mcgdb84_types: List of strings, the mgcdb84 types.\n feature_names_x: List of strings, the features for exchange enhancement\n factor.\n feature_names_css: List of strings, the features for same-spin correlation\n enhancement factor.\n feature_names_cos: List of strings, the features for opposite-spin\n correlation enhancement factor.\n train_validation_test_split: Sequence of 3 floats, the fraction of training,\n validation and test set.\n spin_singlet: Boolean, if True, only spin unpolarized molecules will\n be included in dataset.\n targets: String, the targets used for evaluating WRMSD. Defaults to\n 'mgcdb84_ref', which computes target values from reference values given\n by MCGDB84. Other supported values are:\n * B97X: target values are exchange-correlation energies evaluated by\n B97 exchange.\n num_targets: Integer, the total number of targets used to construct\n train, validation and test set evaluator. Defaults to use all targets with\n specified data types.\n omega: Float, RSH parameter for functional used in SCF calculations.\n alpha: Float, RSH parameter for functional used in SCF calculations.\n beta: Float, RSH parameter for functional used in SCF calculations.\n Default values of omega, alpha, beta are those of wB97M-V functional\n obtained with pyscf.dft.libxc.rsh_coeff('wb97m_v')\n eval_modes: Sequence of 3 strings, evaluation mode for training, validation\n and test evaluators. Possible values are onp, jnp and jit.\n\n Returns:\n List of 3 instances of evaluators.Evaluator, the evaluator for training,\n validation and test losses.\n\n Raises:\n ValueError, if train_validation_test_split has wrong length\n or train_validation_test_split contains negative values\n or train_validation_test_split do not sum to 1.\n \"\"\"\n if (len(train_validation_test_split) != 3\n or any(frac < 0. for frac in train_validation_test_split)\n or abs(sum(train_validation_test_split) - 1.) > 1e-8):\n raise ValueError(\n 'Invalid train_validation_test_split: ', train_validation_test_split)\n\n subset = dataset.Dataset.load_mcgdb84_subset(\n dataset_directory=dataset_directory,\n mgcdb84_types=mcgdb84_types,\n spin_singlet=spin_singlet,\n nrow_property=num_targets)\n\n property_dfs = np.split(\n subset.property_df.sample(frac=1, random_state=0), [\n int(train_validation_test_split[0] * subset.nrow_property),\n int(sum(train_validation_test_split[:2]) * subset.nrow_property)\n ])\n\n evaluator_list = []\n for paritition_index, partition in enumerate(['train', 'validation', 'test']):\n evaluator = evaluators.Evaluator.from_dataset(\n subset=subset.get_subset(\n property_df_subset=property_dfs[paritition_index]),\n feature_names_x=feature_names_x,\n feature_names_css=feature_names_css,\n feature_names_cos=feature_names_cos,\n targets=targets,\n omega=omega,\n alpha=alpha,\n beta=beta,\n eval_mode=eval_modes[paritition_index])\n logging.info('Evaluator on %s set constructed: %s', partition, evaluator)\n evaluator_list.append(evaluator)\n\n return evaluator_list\n\n\ndef make_grid_evaluators(\n features,\n weights,\n targets,\n e_lda_x,\n e_lda_css,\n e_lda_cos,\n signature,\n train_validation_test_split=(0.6, 0.2, 0.2),\n eval_modes=('jit', 'onp', 'onp')):\n \"\"\"Constructs grid evaluators.\"\"\"\n if (len(train_validation_test_split) != 3\n or any(frac < 0. for frac in train_validation_test_split)\n or abs(sum(train_validation_test_split) - 1.) > 1e-8):\n raise ValueError(\n 'Invalid train_validation_test_split: ', train_validation_test_split)\n\n features = {feature_name: np.array(feature)\n for feature_name, feature in features.items()}\n weights = np.array(weights)\n targets = np.array(targets)\n e_lda_x = np.array(e_lda_x)\n e_lda_css = np.array(e_lda_css)\n e_lda_cos = np.array(e_lda_cos)\n\n num_grids = len(weights)\n grid_indices_partition = np.split(\n np.random.RandomState(0).permutation(num_grids), [\n int(train_validation_test_split[0] * num_grids),\n int(sum(train_validation_test_split[:2]) * num_grids)\n ])\n\n evaluator_list = []\n for paritition_index, partition in enumerate(['train', 'validation', 'test']):\n grid_indices = grid_indices_partition[paritition_index]\n evaluator = evaluators.GridEvaluator(\n # make copies to ensure memory layout is contiguous\n features={feature_name: feature[grid_indices].copy()\n for feature_name, feature in features.items()},\n weights=weights[grid_indices].copy(),\n targets=targets[grid_indices].copy(),\n e_lda_x=e_lda_x[grid_indices].copy(),\n e_lda_css=e_lda_css[grid_indices].copy(),\n e_lda_cos=e_lda_cos[grid_indices].copy(),\n signature=signature,\n eval_mode=eval_modes[paritition_index])\n logging.info(\n 'GridEvaluator on %s set constructed: %s', partition, evaluator)\n evaluator_list.append(evaluator)\n\n return evaluator_list\n\n\ndef make_random_functional(\n mutator,\n feature_names_x,\n feature_names_css,\n feature_names_cos,\n num_shared_parameters,\n num_variables,\n num_instructions):\n \"\"\"Makes a random functional with given specifications.\n\n Args:\n mutator: Instance of mutators.XCFunctionalMutator, the mutator used to\n generate random instruction lists.\n feature_names_x: Sequence of strings, the feature names for evaluating\n exchange enhancement factor.\n feature_names_css: Sequence of strings, the feature names for evaluating\n same-spin correlation enhancement factor.\n feature_names_cos: Sequence of strings, the feature names for evaluating\n opposite-spin correlation enhancement factor.\n num_shared_parameters: Integer or sequence of 3 integers, the number of\n shared parameters for each enhancement factor. Defaults to None, which\n uses the number of shared parameters of current enhancement factors.\n num_variables: Integer or sequence of 3 integers, the number of variables\n for each enhancement factor. Defaults to None, which uses the number\n of variables of current enhancement factors.\n num_instructions: Integer, the number of instructions for each enhancement\n factor.\n\n Returns:\n Instance of xc_functionals.XCFunctional, the random functional.\n \"\"\"\n if num_shared_parameters is None or isinstance(num_shared_parameters, int):\n num_shared_parameters_x = num_shared_parameters\n num_shared_parameters_css = num_shared_parameters\n num_shared_parameters_cos = num_shared_parameters\n else:\n (num_shared_parameters_x, num_shared_parameters_css,\n num_shared_parameters_cos) = num_shared_parameters\n\n if num_variables is None or isinstance(num_variables, int):\n num_variables_x = num_variables\n num_variables_css = num_variables\n num_variables_cos = num_variables\n else:\n num_variables_x, num_variables_css, num_variables_cos = num_variables\n\n f_x_base = enhancement_factors.f_empty.make_isomorphic_copy(\n feature_names=feature_names_x,\n num_shared_parameters=num_shared_parameters_x,\n num_variables=num_variables_x)\n f_css_base = enhancement_factors.f_empty.make_isomorphic_copy(\n feature_names=feature_names_css,\n num_shared_parameters=num_shared_parameters_css,\n num_variables=num_variables_css)\n f_cos_base = enhancement_factors.f_empty.make_isomorphic_copy(\n feature_names=feature_names_cos,\n num_shared_parameters=num_shared_parameters_cos,\n num_variables=num_variables_cos)\n\n return xc_functionals.XCFunctional(\n f_x=enhancement_factors.EnhancementFactor(\n feature_names=f_x_base.feature_names,\n shared_parameter_names=f_x_base.shared_parameter_names,\n variable_names=f_x_base.variable_names,\n instruction_list=mutator.mutator_x.randomize_instruction_list(\n f_x_base, num_instructions=num_instructions)[0]),\n f_css=enhancement_factors.EnhancementFactor(\n feature_names=f_css_base.feature_names,\n shared_parameter_names=f_css_base.shared_parameter_names,\n variable_names=f_css_base.variable_names,\n instruction_list=mutator.mutator_css.randomize_instruction_list(\n f_css_base, num_instructions=num_instructions)[0]),\n f_cos=enhancement_factors.EnhancementFactor(\n feature_names=f_cos_base.feature_names,\n shared_parameter_names=f_cos_base.shared_parameter_names,\n variable_names=f_cos_base.variable_names,\n instruction_list=mutator.mutator_cos.randomize_instruction_list(\n f_cos_base, num_instructions=num_instructions)[0]),\n )\n\n\ndef train_functional(functional,\n optimizer,\n num_opt_trials,\n parameters_init=None,\n evaluator_validation=None,\n evaluator_test=None,\n clear_xla_cache=True):\n \"\"\"Trains a given functional form.\n\n Args:\n functional: Instance of xc_functionals.XCFunctional, the functional form\n with parameters to be determined by optimization.\n optimizer: Instance of optimizers.CMAESOptimizer, the optimizer.\n num_opt_trials: Integer, the number of trials for optimization. The final\n results will be determined by the trial with minimum training loss.\n parameters_init: Dict, initial parameters. If not specified, random initial\n parameters will be used.\n evaluator_validation: Instance of evaluators.Evaluator, the evaluator\n of validation loss. If present, the validation loss will be computed.\n evaluator_test: Instance of evaluators.Evaluator, the evaluator\n of test loss. If present, the test loss will be computed.\n clear_xla_cache: Boolean, if True, the XLA cache will be cleared. Only\n relevant if jax.jit is used for evaluations.\n\n Returns:\n Dict, the results of optimization, see CMAESOptimizer.run_optimization.\n If evaluator_validation is specified, the dict will include an additional\n key 'validation_loss' for validation loss.\n \"\"\"\n if clear_xla_cache:\n # NOTE(htm): jax.jit will cache compiled functions with different static\n # arguments. Currently, one has to call the following protected function\n # to clear jit cache.\n xla._xla_callable.cache_clear() # pylint: disable=protected-access\n\n # optimize the functional form with training set\n start = time.time()\n results = optimizer.run_optimization(\n functional,\n num_trials=num_opt_trials,\n parameters_init=parameters_init)\n results['train_loss'] = results.pop('fbest')\n results['train_time'] = time.time() - start\n\n evaluator_list = []\n if evaluator_validation is not None:\n evaluator_list.append(('validation', evaluator_validation))\n if evaluator_test is not None:\n evaluator_list.append(('test', evaluator_test))\n\n for prefix, evaluator in evaluator_list:\n start = time.time()\n\n if results['parameters'] is not None:\n loss = evaluator.get_eval_wrmsd(functional)(**results['parameters'])\n else:\n loss = np.nan\n\n results[f'{prefix}_loss'] = loss\n results[f'{prefix}_time'] = time.time() - start\n\n logging.info('%s WRMSD (kcal/mol): %s', prefix.capitalize(), loss)\n logging.info('Evaluation time for %s WRMSD: %s',\n prefix, results[f'{prefix}_time'])\n\n return results\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"The metric functions for evaluating sequence tagging.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport tf_slim as slim\n\nfrom tensorflow.python.ops import array_ops # pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.ops import math_ops # pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.ops import state_ops # pylint: disable=g-direct-tensorflow-import\n\n\ndef streaming_confusion_matrix(labels, predictions, num_classes, weights=None):\n \"\"\"Calculate a streaming confusion matrix.\n\n Calculates a confusion matrix. For estimation over a stream of data,\n the function creates an `update_op` operation.\n\n Args:\n labels: A `Tensor` of ground truth labels with shape [batch size] and of\n type `int32` or `int64`. The tensor will be flattened if its rank > 1.\n predictions: A `Tensor` of prediction results for semantic labels, whose\n shape is [batch size] and type `int32` or `int64`. The tensor will be\n flattened if its rank > 1.\n num_classes: The possible number of labels the prediction task can have.\n This value must be provided, since a confusion matrix of dimension =\n [num_classes, num_classes] will be allocated.\n weights: Optional `Tensor` whose rank is either 0, or the same rank as\n `labels`, and must be broadcastable to `labels` (i.e., all dimensions must\n be either `1`, or the same as the corresponding `labels` dimension).\n\n Returns:\n total_cm: A `Tensor` representing the confusion matrix.\n update_op: An operation that increments the confusion matrix.\n \"\"\"\n with tf.variable_scope(None, \"streaming_confusion_matrix\",\n [predictions, labels]):\n\n # Local variable to accumulate the predictions in the confusion matrix.\n total_cm = slim.local_variable(\n tf.zeros([num_classes, num_classes], tf.float64),\n name=\"total_confusion_matrix\")\n # Cast the type to int64 required by confusion_matrix_ops.\n predictions = math_ops.cast(predictions, tf.int64)\n labels = math_ops.cast(labels, tf.int64)\n num_classes = math_ops.cast(num_classes, tf.int64)\n\n # Flatten the input if its rank > 1.\n if predictions.get_shape().ndims > 1:\n predictions = array_ops.reshape(predictions, [-1])\n\n if labels.get_shape().ndims > 1:\n labels = array_ops.reshape(labels, [-1])\n\n if (weights is not None) and (weights.get_shape().ndims > 1):\n weights = array_ops.reshape(weights, [-1])\n\n # Accumulate the prediction to current confusion matrix.\n current_cm = tf.math.confusion_matrix(\n labels,\n predictions,\n tf.to_int64(num_classes),\n weights=weights,\n dtype=tf.float64,\n name=\"current_confusion_matrix\")\n update_op = state_ops.assign_add(total_cm, current_cm)\n return total_cm, update_op\n\n\ndef precision(labels,\n predictions,\n num_classes,\n pos_indices=None,\n weights=None,\n average=\"micro\"):\n \"\"\"Multi-class precision metric for Tensorflow.\n\n Args:\n labels: Tensor of tf.int32 or tf.int64 The true labels\n predictions: Tensor of tf.int32 or tf.int64 The predictions, same shape as\n labels\n num_classes: int The number of classes\n pos_indices: list of int, optional The indices of the positive classes,\n default is all\n weights: Tensor of tf.int32, optional Mask, must be of compatible shape with\n labels\n average : str, optional\n \"micro\": counts the total number of true positives, false positives, and\n false negatives for the classes in `pos_indices` and infer the metric\n from it.\n \"macro\": will compute the metric separately for each class in\n `pos_indices` and average. Will not account for class imbalance.\n \"weighted\": will compute the metric separately for each class in\n `pos_indices` and perform a weighted average by the total number of\n true labels for each class.\n\n Returns:\n tuple of (scalar float Tensor, update_op)\n \"\"\"\n cm, op = streaming_confusion_matrix(labels, predictions, num_classes, weights)\n pr, _, _ = metrics_from_confusion_matrix(cm, pos_indices, average=average)\n op, _, _ = metrics_from_confusion_matrix(op, pos_indices, average=average)\n return (pr, op)\n\n\ndef recall(labels,\n predictions,\n num_classes,\n pos_indices=None,\n weights=None,\n average=\"micro\"):\n \"\"\"Multi-class recall metric for Tensorflow.\n\n Args:\n labels : Tensor of tf.int32 or tf.int64 The true labels\n predictions : Tensor of tf.int32 or tf.int64 The predictions, same shape as\n labels\n num_classes : int The number of classes\n pos_indices : list of int, optional The indices of the positive classes,\n default is all\n weights : Tensor of tf.int32, optional Mask, must be of compatible shape\n with labels\n average : str, optional\n \"micro\": counts the total number of true positives, false positives, and\n false negatives for the classes in `pos_indices` and infer the metric\n from it.\n \"macro\": will compute the metric separately for each class in\n `pos_indices` and average. Will not account for class imbalance.\n \"weighted\": will compute the metric separately for each class in\n `pos_indices` and perform a weighted average by the total number of\n true labels for each class.\n\n Returns:\n tuple of (scalar float Tensor, update_op)\n \"\"\"\n cm, op = streaming_confusion_matrix(labels, predictions, num_classes, weights)\n _, re, _ = metrics_from_confusion_matrix(cm, pos_indices, average=average)\n _, op, _ = metrics_from_confusion_matrix(op, pos_indices, average=average)\n return (re, op)\n\n\ndef f1(labels,\n predictions,\n num_classes,\n pos_indices=None,\n weights=None,\n average=\"micro\"):\n return fbeta(labels, predictions, num_classes, pos_indices, weights, average)\n\n\ndef fbeta(labels,\n predictions,\n num_classes,\n pos_indices=None,\n weights=None,\n average=\"micro\",\n beta=1):\n \"\"\"Multi-class fbeta metric for Tensorflow.\n\n Args:\n labels : Tensor of tf.int32 or tf.int64 The true labels\n predictions : Tensor of tf.int32 or tf.int64 The predictions, same shape as\n labels\n num_classes : int The number of classes\n pos_indices : list of int, optional The indices of the positive classes,\n default is all\n weights : Tensor of tf.int32, optional Mask, must be of compatible shape\n with labels\n average : str, optional\n \"micro\": counts the total number of true positives, false positives, and\n false negatives for the classes in `pos_indices` and infer the metric\n from it.\n \"macro\": will compute the metric separately for each class in\n `pos_indices` and average. Will not account for class imbalance.\n \"weighted\": will compute the metric separately for each class in\n `pos_indices` and perform a weighted average by the total number of\n true labels for each class.\n beta : int, optional Weight of precision in harmonic mean\n\n Returns:\n tuple of (scalar float Tensor, update_op)\n \"\"\"\n cm, op = streaming_confusion_matrix(labels, predictions, num_classes, weights)\n _, _, fbeta_score = metrics_from_confusion_matrix(\n cm, pos_indices, average=average, beta=beta)\n _, _, op = metrics_from_confusion_matrix(\n op, pos_indices, average=average, beta=beta)\n return (fbeta_score, op)\n\n\ndef safe_div(numerator, denominator):\n \"\"\"Does safe division, returns 0 if denominator is 0.\"\"\"\n numerator, denominator = tf.to_float(numerator), tf.to_float(denominator)\n zeros = tf.zeros_like(numerator, dtype=numerator.dtype)\n denominator_is_zero = tf.equal(denominator, zeros)\n return tf.where(denominator_is_zero, zeros, numerator / denominator)\n\n\ndef pr_re_fbeta(cm, pos_indices, beta=1):\n \"\"\"Uses a confusion matrix to compute precision, recall and fbeta.\"\"\"\n num_classes = cm.shape[0]\n neg_indices = [i for i in range(num_classes) if i not in pos_indices]\n cm_mask = np.ones([num_classes, num_classes])\n cm_mask[neg_indices, neg_indices] = 0\n diag_sum = tf.reduce_sum(tf.diag_part(cm * cm_mask))\n\n cm_mask = np.ones([num_classes, num_classes])\n cm_mask[:, neg_indices] = 0\n tot_pred = tf.reduce_sum(cm * cm_mask)\n\n cm_mask = np.ones([num_classes, num_classes])\n cm_mask[neg_indices, :] = 0\n tot_gold = tf.reduce_sum(cm * cm_mask)\n\n pr = safe_div(diag_sum, tot_pred)\n re = safe_div(diag_sum, tot_gold)\n fbeta_score = safe_div((1. + beta**2) * pr * re, beta**2 * pr + re)\n\n return pr, re, fbeta_score\n\n\ndef metrics_from_confusion_matrix(cm,\n pos_indices=None,\n average=\"micro\",\n beta=1):\n \"\"\"Generates Precision, Recall and F1 from the confusion matrix.\n\n Args:\n cm: tf.Tensor of type tf.int32, of shape (num_classes, num_classes) The\n streaming confusion matrix.\n pos_indices: list of int, optional The indices of the positive classes\n average: str, optional \"micro\", \"macro\" or \"weighted\"\n beta: int, optional Weight of precision in harmonic mean\n\n Returns:\n the confusion_matrix\n \"\"\"\n num_classes = cm.shape[0]\n if pos_indices is None:\n pos_indices = [i for i in range(num_classes)]\n\n if average == \"micro\":\n return pr_re_fbeta(cm, pos_indices, beta)\n elif average in {\"macro\", \"weighted\"}:\n precisions, recalls, fbetas, n_golds = [], [], [], []\n for idx in pos_indices:\n pr, re, fbeta_score = pr_re_fbeta(cm, [idx], beta)\n precisions.append(pr)\n recalls.append(re)\n fbetas.append(fbeta_score)\n cm_mask = np.zeros([num_classes, num_classes])\n cm_mask[idx, :] = 1\n n_golds.append(tf.to_float(tf.reduce_sum(cm * cm_mask)))\n\n if average == \"macro\":\n pr = tf.reduce_mean(precisions)\n re = tf.reduce_mean(recalls)\n fbeta_score = tf.reduce_mean(fbetas)\n return pr, re, fbeta_score\n if average == \"weighted\":\n n_gold = tf.reduce_sum(n_golds)\n pr_sum = sum(p * n for p, n in zip(precisions, n_golds))\n pr = safe_div(pr_sum, n_gold)\n re_sum = sum(r * n for r, n in zip(recalls, n_golds))\n re = safe_div(re_sum, n_gold)\n fbeta_sum = sum(f * n for f, n in zip(fbetas, n_golds))\n fbeta_score = safe_div(fbeta_sum, n_gold)\n return pr, re, fbeta_score\n\n else:\n raise NotImplementedError()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Implementation of DualDICE https://openreview.net/pdf?id=SygrvzwniE .\"\"\"\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nfrom value_dice import keras_utils\nfrom value_dice import twin_sac\n\n\nEPS = np.finfo(np.float32).eps\n\n\ndef weighted_softmax(x, weights, axis=0):\n x = x - tf.reduce_max(x, axis=axis)\n return weights * tf.exp(x) / tf.reduce_sum(\n weights * tf.exp(x), axis=axis, keepdims=True)\n\n\nclass ValueDICE(object):\n \"\"\"Class that implements DualDICE training.\"\"\"\n\n def __init__(self, state_dim, action_dim, log_interval, nu_lr, actor_lr,\n alpha_init, hidden_size):\n \"\"\"Creates a DualDICE object.\n\n Args:\n state_dim: State size.\n action_dim: Action size.\n log_interval: Log losses every N steps.\n nu_lr: nu network learning rate.\n actor_lr: actor learning rate.\n alpha_init: Initial temperature value.\n hidden_size: A number of hidden units.\n \"\"\"\n\n self.nu_net = tf.keras.Sequential([\n tf.keras.layers.Dense(\n hidden_size,\n input_shape=(state_dim + action_dim,),\n activation=tf.nn.relu,\n kernel_initializer='orthogonal'),\n tf.keras.layers.Dense(\n hidden_size, activation=tf.nn.relu,\n kernel_initializer='orthogonal'),\n tf.keras.layers.Dense(\n 1, kernel_initializer='orthogonal', use_bias=False)\n ])\n\n self.log_interval = log_interval\n\n self.avg_loss = tf.keras.metrics.Mean('dual dice loss', dtype=tf.float32)\n self.avg_ratio = tf.keras.metrics.Mean('dual dice ratio', dtype=tf.float32)\n\n self.avg_nu_expert = tf.keras.metrics.Mean(\n 'dual dice expert', dtype=tf.float32)\n self.avg_nu_rb = tf.keras.metrics.Mean('dual dice nu rb', dtype=tf.float32)\n\n self.nu_reg_metric = tf.keras.metrics.Mean('nu reg', dtype=tf.float32)\n\n self.nu_optimizer = tf.keras.optimizers.Adam(learning_rate=nu_lr)\n\n self.actor = twin_sac.Actor(state_dim, action_dim)\n self.actor_optimizer = tf.keras.optimizers.Adam(learning_rate=actor_lr)\n self.avg_actor_loss = tf.keras.metrics.Mean('actor_loss', dtype=tf.float32)\n self.avg_alpha_loss = tf.keras.metrics.Mean('alpha_loss', dtype=tf.float32)\n self.avg_actor_entropy = tf.keras.metrics.Mean(\n 'actor_entropy', dtype=tf.float32)\n self.avg_alpha = tf.keras.metrics.Mean('alpha', dtype=tf.float32)\n\n self.log_alpha = tf.Variable(tf.math.log(alpha_init), trainable=True)\n self.alpha_optimizer = tf.keras.optimizers.Adam()\n\n @property\n def alpha(self):\n return tf.exp(self.log_alpha)\n\n @tf.function\n def update(self,\n expert_dataset_iter,\n policy_dataset_iter,\n discount,\n replay_regularization=0.05,\n nu_reg=10.0):\n \"\"\"A function that updates nu network.\n\n When replay regularization is non-zero, it learns\n (d_pi * (1 - replay_regularization) + d_rb * replay_regulazation) /\n (d_expert * (1 - replay_regularization) + d_rb * replay_regulazation)\n instead.\n\n Args:\n expert_dataset_iter: An tensorflow graph iteratable over expert data.\n policy_dataset_iter: An tensorflow graph iteratable over training policy\n data, used for regularization.\n discount: An MDP discount.\n replay_regularization: A fraction of samples to add from a replay buffer.\n nu_reg: A grad penalty regularization coefficient.\n \"\"\"\n\n (expert_states, expert_actions,\n expert_next_states) = expert_dataset_iter.get_next()\n\n expert_initial_states = expert_states\n\n rb_states, rb_actions, rb_next_states, _, _ = policy_dataset_iter.get_next(\n )[0]\n\n with tf.GradientTape(\n watch_accessed_variables=False, persistent=True) as tape:\n tape.watch(self.actor.variables)\n tape.watch(self.nu_net.variables)\n\n _, policy_next_actions, _ = self.actor(expert_next_states)\n _, rb_next_actions, rb_log_prob = self.actor(rb_next_states)\n\n _, policy_initial_actions, _ = self.actor(expert_initial_states)\n\n # Inputs for the linear part of DualDICE loss.\n expert_init_inputs = tf.concat(\n [expert_initial_states, policy_initial_actions], 1)\n\n expert_inputs = tf.concat([expert_states, expert_actions], 1)\n expert_next_inputs = tf.concat([expert_next_states, policy_next_actions],\n 1)\n\n rb_inputs = tf.concat([rb_states, rb_actions], 1)\n rb_next_inputs = tf.concat([rb_next_states, rb_next_actions], 1)\n\n expert_nu_0 = self.nu_net(expert_init_inputs)\n expert_nu = self.nu_net(expert_inputs)\n expert_nu_next = self.nu_net(expert_next_inputs)\n\n rb_nu = self.nu_net(rb_inputs)\n rb_nu_next = self.nu_net(rb_next_inputs)\n\n expert_diff = expert_nu - discount * expert_nu_next\n rb_diff = rb_nu - discount * rb_nu_next\n\n linear_loss_expert = tf.reduce_mean(expert_nu_0 * (1 - discount))\n\n linear_loss_rb = tf.reduce_mean(rb_diff)\n\n rb_expert_diff = tf.concat([expert_diff, rb_diff], 0)\n rb_expert_weights = tf.concat([\n tf.ones(expert_diff.shape) * (1 - replay_regularization),\n tf.ones(rb_diff.shape) * replay_regularization\n ], 0)\n\n rb_expert_weights /= tf.reduce_sum(rb_expert_weights)\n non_linear_loss = tf.reduce_sum(\n tf.stop_gradient(\n weighted_softmax(rb_expert_diff, rb_expert_weights, axis=0)) *\n rb_expert_diff)\n\n linear_loss = (\n linear_loss_expert * (1 - replay_regularization) +\n linear_loss_rb * replay_regularization)\n\n loss = (non_linear_loss - linear_loss)\n\n alpha = tf.random.uniform(shape=(expert_inputs.shape[0], 1))\n\n nu_inter = alpha * expert_inputs + (1 - alpha) * rb_inputs\n nu_next_inter = alpha * expert_next_inputs + (1 - alpha) * rb_next_inputs\n\n nu_inter = tf.concat([nu_inter, nu_next_inter], 0)\n\n with tf.GradientTape(watch_accessed_variables=False) as tape2:\n tape2.watch(nu_inter)\n nu_output = self.nu_net(nu_inter)\n nu_grad = tape2.gradient(nu_output, [nu_inter])[0] + EPS\n nu_grad_penalty = tf.reduce_mean(\n tf.square(tf.norm(nu_grad, axis=-1, keepdims=True) - 1))\n\n nu_loss = loss + nu_grad_penalty * nu_reg\n pi_loss = -loss + keras_utils.orthogonal_regularization(self.actor.trunk)\n\n nu_grads = tape.gradient(nu_loss, self.nu_net.variables)\n pi_grads = tape.gradient(pi_loss, self.actor.variables)\n\n self.nu_optimizer.apply_gradients(zip(nu_grads, self.nu_net.variables))\n self.actor_optimizer.apply_gradients(zip(pi_grads, self.actor.variables))\n\n del tape\n\n self.avg_nu_expert(expert_nu)\n self.avg_nu_rb(rb_nu)\n\n self.nu_reg_metric(nu_grad_penalty)\n self.avg_loss(loss)\n\n self.avg_actor_loss(pi_loss)\n self.avg_actor_entropy(-rb_log_prob)\n\n if tf.equal(self.nu_optimizer.iterations % self.log_interval, 0):\n tf.summary.scalar(\n 'train dual dice/loss',\n self.avg_loss.result(),\n step=self.nu_optimizer.iterations)\n keras_utils.my_reset_states(self.avg_loss)\n\n tf.summary.scalar(\n 'train dual dice/nu expert',\n self.avg_nu_expert.result(),\n step=self.nu_optimizer.iterations)\n keras_utils.my_reset_states(self.avg_nu_expert)\n\n tf.summary.scalar(\n 'train dual dice/nu rb',\n self.avg_nu_rb.result(),\n step=self.nu_optimizer.iterations)\n keras_utils.my_reset_states(self.avg_nu_rb)\n\n tf.summary.scalar(\n 'train dual dice/nu reg',\n self.nu_reg_metric.result(),\n step=self.nu_optimizer.iterations)\n keras_utils.my_reset_states(self.nu_reg_metric)\n\n if tf.equal(self.actor_optimizer.iterations % self.log_interval, 0):\n tf.summary.scalar(\n 'train sac/actor_loss',\n self.avg_actor_loss.result(),\n step=self.actor_optimizer.iterations)\n keras_utils.my_reset_states(self.avg_actor_loss)\n\n tf.summary.scalar(\n 'train sac/actor entropy',\n self.avg_actor_entropy.result(),\n step=self.actor_optimizer.iterations)\n keras_utils.my_reset_states(self.avg_actor_entropy)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom absl import logging\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\nfrom cold_posterior_flax.cifar10 import train\nfrom cold_posterior_flax.cifar10.configs import default\n\n\nclass TrainTest(tf.test.TestCase):\n \"\"\"Test cases for CIFAR10.\"\"\"\n\n def test_train_sgmcmc(self):\n config = default.get_config()\n config.algorithm = 'sgmcmc'\n config.optimizer = 'sym_euler'\n config.arch = 'wrn8_1'\n config.batch_size = 2\n config.num_epochs = 1\n # TODO(basv): include evaluation in testing (mock_data is preventing this).\n config.do_eval = False\n workdir = self.create_tempdir().full_path\n with tfds.testing.mock_data(num_examples=1):\n train.train_and_evaluate(config, workdir)\n logging.info('workdir content: %s', tf.io.gfile.listdir(workdir))\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport concurrent.futures\nimport math\nimport re\n\nfrom absl import flags\nfrom absl.testing import absltest\nfrom absl.testing import flagsaver\nfrom absl.testing import parameterized\nimport jax\nfrom jax import numpy as jnp\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom aqt.jax.wmt_mlperf import train\nfrom aqt.jax.wmt_mlperf import training_hparams\nfrom aqt.jax.wmt_mlperf.hparams_configs.experimental import minimal_model_8bit_weights_and_auto_acts\nfrom aqt.jax.wmt_mlperf.hparams_configs.experimental import minimal_model_bfloat16\nfrom aqt.jax.wmt_mlperf.training_hparams_generator_lib import BaseConfigSize\nfrom aqt.jax.wmt_mlperf.training_hparams_generator_lib import create_training_hparams_from_flags\nfrom aqt.utils import hparams_utils as os_hparams_utils\n\nFLAGS = flags.FLAGS\n\n\ndef create_1x1():\n return np.ones((1, 1), dtype=np.int64)\n\n\ndef create_mock_data():\n \"\"\"Create the absolute smallest dataset that can be supplied to the training loop.\"\"\"\n\n # Note that not all these keys are necessary for each kind of dataset\n # (train, eval, predict),\n # but it doesn't hurt to have them.\n data = {\n 'inputs': create_1x1(),\n 'inputs_position': create_1x1(),\n 'inputs_segmentation': create_1x1(),\n 'targets': create_1x1(),\n 'targets_position': create_1x1(),\n 'targets_segmentation': create_1x1(),\n }\n dataset = tf.data.Dataset.from_tensor_slices(data).batch(1)\n return dataset\n\n\n# The training loop requires a decoder for its target language (ie, word\n# index->human-readable string) to produce human-readable output during\n# evaluation, so we mock the decoder.\nclass MockEncoder():\n \"\"\"Mocks the tensorflow_text.SentencepieceTokenizer used in input_pipeline.py.\"\"\"\n\n def vocab_size(self):\n # Not '1' so that 'low_confidence' calculation in train.py\n # doesn't divide-by-zero.\n return 2\n\n def detokenize(self, _):\n return tf.constant('<mock>')\n\n\n# TODO(wanglisa): Once the remaining transformer kwargs are moved to flags,\n# these test cases can all be specified in terms of flags (and thus we gain\n# additional test coverage of the flag-processing functions in\n# training_hparams.py).\nclass TrainTest(parameterized.TestCase):\n\n def setUp(self):\n super().setUp()\n self.datasets = train.Datasets(\n train_ds=create_mock_data(),\n eval_ds_dict={'mock_data': create_mock_data()},\n train_eval_ds=create_mock_data(),\n predict_ds_dict={'mock_data': create_mock_data()},\n encoder=MockEncoder())\n\n @parameterized.named_parameters(\n dict(\n testcase_name='minimal_bfloat16',\n hparams_config_filename=minimal_model_bfloat16),)\n def test_train_with_config_file(self, hparams_config_filename):\n with flagsaver.flagsaver(\n num_eval_steps=1,\n eval_batch_size=1,\n max_target_length=1,\n eval_dataset_name='mock_data',\n max_eval_target_length=1,\n max_predict_length=1,\n model_dir=FLAGS.test_tmpdir,\n ):\n hparams = os_hparams_utils.load_dataclass_from_config_dict(\n training_hparams.TrainingHParams,\n hparams_config_filename.get_config())\n with concurrent.futures.ThreadPoolExecutor(max_workers=1) as io_executor:\n train.run_training(\n datasets=self.datasets,\n hparams=hparams,\n io_executor=io_executor,\n )\n\n def test_checkpointing(self):\n hparams = os_hparams_utils.load_dataclass_from_config_dict(\n training_hparams.TrainingHParams,\n minimal_model_8bit_weights_and_auto_acts.get_config())\n training_state_initial = train.TrainingState.initialize(\n encoder=self.datasets.encoder, hparams=hparams)\n\n ckpt_dir = FLAGS.test_tmpdir + '/ckpt_dir'\n tf.io.gfile.makedirs(ckpt_dir)\n # Delete existing files in the temp directory to clear out old checkpoints.\n for dir_name, _, file_names in tf.io.gfile.walk(ckpt_dir):\n for filename in file_names:\n file_path = tf.io.gfile.join(dir_name, filename)\n tf.io.gfile.remove(file_path)\n\n training_state, _ = train.run_train_step(\n training_state=training_state_initial,\n batch=next(iter(self.datasets.train_ds)),\n step=0,\n hparams=hparams)\n\n self.assertFalse(train.does_checkpoint_exist(ckpt_dir))\n training_state.save_checkpoint(model_dir=ckpt_dir, step=0)\n self.assertTrue(train.does_checkpoint_exist(ckpt_dir))\n\n self.assertNotEqual(training_state.flax_state,\n training_state_initial.flax_state)\n with np.testing.assert_raises(AssertionError):\n np.testing.assert_array_equal(training_state.dropout_rngs,\n training_state_initial.dropout_rngs)\n training_state_restored = training_state_initial.restore_checkpoint(\n model_dir=ckpt_dir)\n\n leaf_equality_tree = jax.tree_multimap(lambda x, y: jnp.all(x == y),\n training_state.flax_state,\n training_state_restored.flax_state)\n self.assertTrue(\n all(jax.tree_leaves(leaf_equality_tree)),\n 'Training state was altered during restoration.')\n\n np.testing.assert_array_equal(training_state.dropout_rngs,\n training_state_restored.dropout_rngs)\n\n\nclass LearningRateSchedulerTest(absltest.TestCase):\n\n def setUp(self):\n super().setUp()\n self.hparams = training_hparams.LearningRateSchedulerHParams(\n factors='',\n base_learning_rate=2.0,\n warmup_steps=0,\n decay_factor=None,\n steps_per_decay=None,\n steps_per_cycle=None)\n\n def test_constant(self):\n hparams = self.hparams\n hparams.factors = 'constant'\n schedule = train.create_learning_rate_scheduler(hparams)\n self.assertEqual(schedule(0), 2.0)\n self.assertEqual(schedule(100), 2.0)\n\n def test_linear_warmup(self):\n hparams = self.hparams\n hparams.factors = 'constant*linear_warmup'\n hparams.warmup_steps = 10\n schedule = train.create_learning_rate_scheduler(hparams)\n self.assertEqual(schedule(0), 0.0)\n self.assertEqual(schedule(5), 2.0 / 2)\n self.assertEqual(schedule(10), 2.0)\n self.assertEqual(schedule(100), 2.0)\n\n def test_rsqrt_decay(self):\n hparams = self.hparams\n hparams.factors = 'constant*rsqrt_decay'\n hparams.warmup_steps = 9\n hparams.base_learning_rate = 1.0\n schedule = train.create_learning_rate_scheduler(hparams)\n self.assertEqual(schedule(0), 1 / math.sqrt(9))\n self.assertEqual(schedule(9), 1 / math.sqrt(9))\n self.assertEqual(schedule(100), 1 / math.sqrt(100))\n\n def test_mlperf_schedule(self):\n # Parameters modified slightly from the defaults to avoid dealing with\n # floating point error considerations when taking square roots.\n hparams = training_hparams.LearningRateSchedulerHParams(\n factors='constant * linear_warmup * rsqrt_decay',\n base_learning_rate=0.5,\n warmup_steps=100,\n decay_factor=0.5,\n steps_per_decay=20000,\n steps_per_cycle=100000)\n schedule = train.create_learning_rate_scheduler(hparams)\n self.assertEqual(schedule(0), 0.0)\n self.assertEqual(schedule(50), 0.5 / 2 * 1 / math.sqrt(100))\n self.assertEqual(schedule(100), 0.5 * 1 / math.sqrt(100))\n self.assertEqual(schedule(900), 0.5 * 1 / math.sqrt(900))\n\n\nclass BestCheckpointTest(parameterized.TestCase):\n\n def setUp(self):\n super().setUp()\n self.model_dir = FLAGS.test_tmpdir + '/model_dir'\n tf.io.gfile.makedirs(self.model_dir)\n # Delete existing files in the temp directory to clear out old checkpoints.\n for dir_name, _, file_names in tf.io.gfile.walk(self.model_dir):\n for filename in file_names:\n file_path = tf.io.gfile.join(dir_name, filename)\n tf.io.gfile.remove(file_path)\n\n def save_checkpoint(self, loss):\n with flagsaver.flagsaver(base_config_size=BaseConfigSize.MINIMAL_MODEL):\n hparams = create_training_hparams_from_flags()\n training_state = train.TrainingState.initialize(\n encoder=MockEncoder(), hparams=hparams)\n train.save_best_checkpoint(\n model_dir=self.model_dir, training_state=training_state, loss=loss)\n\n def get_model_dir_files(self):\n filenames = list(tf.io.gfile.walk(self.model_dir))[0][2]\n return filenames\n\n def get_checkpoint(self):\n \"\"\"Gets the name of a saved checkpoint.\"\"\"\n files = self.get_model_dir_files()\n # Test there is exactly one saved checkpoint.\n self.assertLen(\n files, 1, f'Expected exactly one checkpoint to be found, got {files}.')\n\n # Extract the loss associated with the checkpoint.\n checkpoint_match = re.match(r'.*best_checkpoint_eval_loss_(.*)$',\n str(files[0]))\n self.assertIsNotNone(checkpoint_match)\n self.assertLen(checkpoint_match.groups(), 1)\n return checkpoint_match.groups()[0]\n\n def test_min_loss_saved(self):\n self.save_checkpoint(2.0)\n self.save_checkpoint(1.0)\n self.save_checkpoint(3.0)\n self.assertEqual(self.get_checkpoint(), '1.0')\n\n @parameterized.named_parameters(\n dict(testcase_name='nan', bad_value=math.nan),\n dict(testcase_name='inf', bad_value=math.inf),\n dict(testcase_name='-inf', bad_value=-math.inf))\n def test_nonfinite_ignored(self, bad_value):\n self.save_checkpoint(2.0)\n self.save_checkpoint(bad_value)\n self.save_checkpoint(1.0)\n self.save_checkpoint(3.0)\n self.assertEqual(self.get_checkpoint(), '1.0')\n\n def test_duplicate_loss(self):\n self.save_checkpoint(1.0)\n self.save_checkpoint(2.0)\n self.save_checkpoint(1.0)\n self.save_checkpoint(3.0)\n self.assertEqual(self.get_checkpoint(), '1.0')\n\n def test_no_checkpoint_saved_if_all_nan(self):\n for _ in range(5):\n self.save_checkpoint(math.nan)\n self.assertEmpty(self.get_model_dir_files())\n\n\nif __name__ == '__main__':\n absltest.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tabular contrastive learner.\"\"\"\n\nfrom typing import Optional, Union\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nfrom tf_agents import specs\n\n\nclass TabularBCEnergy(tf.keras.Model):\n \"\"\"Tabular behavioral cloning with contrastive Fourier features.\"\"\"\n\n def __init__(self,\n dataset_spec,\n gamma,\n embed_dim = 64,\n fourier_dim = None,\n embed_learning_rate = 0.01,\n learning_rate = 0.01,\n finetune = False):\n \"\"\"Initializes the solver.\n\n Args:\n dataset_spec: The spec of the dataset that will be given.\n gamma: The discount factor to use.\n embed_dim: State embedder dimensioin.\n fourier_dim: Fourier feature dimensioin.\n embed_learning_rate: Representation learning rate.\n learning_rate: Policy learning rate.\n finetune: Whether to finetune fourier feature during policy learning.\n \"\"\"\n super().__init__()\n self._gamma = gamma\n self._reward_fn = lambda env_step: env_step.reward\n\n # Get number of states/actions.\n observation_spec = dataset_spec.observation\n action_spec = dataset_spec.action\n self._num_states = observation_spec.maximum + 1\n self._num_actions = action_spec.maximum + 1\n\n self._data_transition = np.zeros(\n [self._num_states, self._num_states, self._num_actions],\n dtype=np.float32)\n self._state_prior = np.zeros([self._num_states], dtype=np.float32)\n self._embed_dim = min(embed_dim, self._num_states)\n self._fourier_dim = fourier_dim or self._embed_dim\n\n # Initialize embed parameters.\n self._state_embedder = tf.Variable(\n tf.random.truncated_normal([self._num_states, self._embed_dim]))\n self._state_action_embedder = tf.Variable(\n tf.random.truncated_normal(\n [self._num_states, self._num_actions, self._embed_dim]))\n\n # Initialize policy parameters.\n if self._fourier_dim:\n self._omega = tf.Variable(\n tf.random.normal([self._fourier_dim, self._embed_dim]),\n trainable=finetune)\n self._shift = tf.Variable(\n tf.random.uniform([self._fourier_dim], minval=0, maxval=2 * 3.14159),\n trainable=finetune)\n self.average_embed = tf.Variable(\n tf.zeros([self._embed_dim]), trainable=False)\n self.average_square = tf.Variable(\n tf.ones([self._embed_dim]), trainable=False)\n\n self._embed_policy = tf.Variable(\n tf.zeros([self._fourier_dim or self._embed_dim, self._num_actions]))\n\n self._embed_optimizer = tf.keras.optimizers.Adam(embed_learning_rate)\n self._optimizer = tf.keras.optimizers.Adam(learning_rate)\n\n def _get_index(self, observation, action):\n return observation * self._num_actions + action\n\n def _state_fourier(self, observation):\n embed = tf.gather(self._state_embedder, observation)\n if not self._fourier_dim:\n return embed\n\n average_embed = self.average_embed\n average_square = self.average_square\n stddev_embed = tf.sqrt(tf.maximum(1e-8, average_square - average_embed**2))\n normalized_omegas = self._omega / stddev_embed[None, :]\n projection = tf.matmul(\n embed - tf.stop_gradient(average_embed),\n normalized_omegas,\n transpose_b=True)\n projection /= self._embed_dim**0.5\n embed_linear = tf.math.cos(projection + self._shift)\n self.update_moving_averages(embed)\n return embed_linear\n\n def _state_action_fourier(self, observation, action):\n embed = tf.gather_nd(self._state_action_embedder,\n tf.stack([observation, action], axis=-1))\n if self._fourier_dim:\n embed = tf.math.cos(\n tf.matmul(embed, self._omega, transpose_b=True) +\n self._shift[None, :])\n return embed\n\n def prepare_datasets(self, dataset, expert_dataset):\n episodes, valid_steps = dataset.get_all_episodes()\n for episode_num in range(tf.shape(valid_steps)[0]):\n for step_num in range(tf.shape(valid_steps)[1] - 1):\n this_step = tf.nest.map_structure(lambda t: t[episode_num, step_num], # pylint: disable=cell-var-from-loop\n episodes)\n next_step = tf.nest.map_structure(\n lambda t: t[episode_num, step_num + 1], episodes) # pylint: disable=cell-var-from-loop\n if this_step.is_last() or not valid_steps[episode_num, step_num]: # pylint: disable=cell-var-from-loop\n continue\n self._state_prior[next_step.observation] += 1.\n self._data_transition[this_step.observation, next_step.observation,\n this_step.action] += 1.\n self._data_transition = tf.math.divide_no_nan(\n self._data_transition,\n tf.reduce_sum(self._data_transition, axis=1, keepdims=True))\n self._state_prior = self._state_prior / np.sum(self._state_prior)\n\n def update_moving_averages(self, embeds):\n tt = 0.0005\n _ = self.average_embed.assign((1 - tt) * self.average_embed +\n tt * tf.reduce_mean(embeds, [0])),\n _ = self.average_square.assign((1 - tt) * self.average_square +\n tt * tf.reduce_mean(embeds**2, [0]))\n\n @tf.function\n def train_embed(self, transitions):\n this_step = tf.nest.map_structure(lambda t: t[:, 0, Ellipsis], transitions)\n next_step = tf.nest.map_structure(lambda t: t[:, 1, Ellipsis], transitions)\n\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n tape.watch(self._state_embedder)\n tape.watch(self._state_action_embedder)\n\n this_embed = tf.gather(self._state_embedder, this_step.observation)\n next_embed = tf.gather_nd(\n self._state_action_embedder,\n tf.stack([next_step.observation, this_step.action], axis=-1))\n all_next_embed = tf.gather(\n self._state_action_embedder, this_step.action, axis=1)\n pos_loss = tf.reduce_sum(-0.5 * (this_embed - next_embed)**2, axis=-1)\n neg_loss = tfp.math.reduce_weighted_logsumexp(\n tf.reduce_sum(\n -0.5 * (this_embed[None, Ellipsis] - all_next_embed)**2, axis=-1),\n w=self._state_prior[:, None],\n axis=0)\n prior = tf.math.log(\n tf.gather(self._state_prior, next_step.observation) + 1e-8)\n loss = tf.reduce_mean(prior - pos_loss + neg_loss)\n\n grads = tape.gradient(loss,\n [self._state_embedder, self._state_action_embedder])\n self._embed_optimizer.apply_gradients(\n zip(grads, [self._state_embedder, self._state_action_embedder]))\n\n data_transition = tf.gather_nd(\n self._data_transition,\n tf.stack(\n [this_step.observation, next_step.observation, this_step.action],\n axis=-1))\n kld = tf.reduce_sum(\n data_transition * (tf.math.log(data_transition + 1e-8) -\n (prior - pos_loss + neg_loss)),\n axis=-1)\n return {\n 'loss': loss,\n 'pos': tf.reduce_mean(pos_loss),\n 'neg': tf.reduce_mean(neg_loss),\n 'kld': tf.reduce_mean(kld),\n }\n\n @tf.function\n def train_step(self, transitions):\n this_step = tf.nest.map_structure(lambda t: t[:, 0, Ellipsis], transitions)\n next_step = tf.nest.map_structure(lambda t: t[:, 1, Ellipsis], transitions)\n variables = [self._embed_policy]\n if self._fourier_dim:\n variables += [self._omega, self._shift]\n with tf.GradientTape(watch_accessed_variables=False) as tape2:\n tape2.watch(variables)\n embed = self._state_fourier(this_step.observation)\n with tf.GradientTape(\n watch_accessed_variables=False, persistent=True) as tape1:\n tape1.watch(self._embed_policy)\n embed_policy = tf.nn.softmax(\n tf.matmul(embed, self._embed_policy), axis=-1)\n action = tf.reduce_sum(\n embed_policy * tf.one_hot(this_step.action, self._num_actions), -1)\n neg_ll = tf.reduce_mean(-tf.math.log(action + 1e-8))\n loss = tf.reduce_sum(tape1.gradient(neg_ll, self._embed_policy)**2)\n\n grads = tape2.gradient(loss, variables)\n self._optimizer.apply_gradients(zip(grads, variables))\n\n embed = self._state_fourier(this_step.observation)\n next_embed = self._state_action_fourier(next_step.observation,\n this_step.action)\n embed_transition = (\n tf.math.sqrt(2. / self._fourier_dim) *\n tf.reduce_sum(embed * next_embed, axis=-1))\n data_transition = tf.gather_nd(\n self._data_transition,\n tf.stack(\n [this_step.observation, next_step.observation, this_step.action],\n axis=-1))\n tvd = tf.reduce_mean(tf.abs(embed_transition - data_transition))\n return {'loss': loss, 'tvd': tvd}\n\n def get_policy(self):\n\n def policy_fn(observation, dtype=tf.int32):\n if tf.rank(observation) < 1:\n observation = [observation]\n\n embed = self._state_fourier(observation)\n distribution = tf.nn.softmax(\n tf.matmul(embed, self._embed_policy), axis=-1)\n\n policy_info = {'distribution': distribution}\n return (tfp.distributions.Categorical(probs=distribution,\n dtype=dtype), policy_info)\n\n policy_info_spec = {\n 'log_probability':\n specs.TensorSpec([], tf.float32),\n 'distribution':\n specs.BoundedTensorSpec([self._num_actions],\n tf.float32,\n minimum=0.0,\n maximum=1.0)\n }\n return policy_fn, policy_info_spec\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"PathNet building blocks.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v1 as tf\n\nfrom tensorflow.compat.v1.keras import layers\nfrom tensorflow.compat.v1.keras import models\n\n\nclass ModelHeadComponent(object):\n \"\"\"Component that computes the task loss.\"\"\"\n\n def __init__(self, loss_fn, auxiliary_loss_fn=None):\n \"\"\"Constructor.\n\n Args:\n loss_fn: function to compute task loss. Given two tf.Tensors of the same\n shape, corresponding to a batch of labels and a batch of model\n predictions respectively, `loss_fn` should return a scalar loss.\n auxiliary_loss_fn: function to compute auxiliary losses or None. If\n a function is provided, it will receive as the single argument the\n `state` passed to `__call__`. The scalar value returned from\n `auxiliary_loss_fn` will be added to `task_loss`. Note that the\n `auxiliary_loss_fn` can take into account more than just the `state`:\n if it is created during construction of the PathNet, it can access\n parts of the PathNet from the outer scope e.g. components and routers.\n \"\"\"\n\n self.name = 'Head'\n self.loss_fn = loss_fn\n self.auxiliary_loss_fn = auxiliary_loss_fn\n\n def __call__(self, state):\n \"\"\"Calls the component to compute the task loss.\n\n Args:\n state: a dictionary with keys: 'in_tensor' containing a batch of\n predictions, and 'labels' containing a batch of labels.\n\n Returns:\n A dictionary with the scalar task loss under the 'task_loss' key.\n \"\"\"\n predictions = state['in_tensor']\n labels = state['labels']\n\n task_loss = self.loss_fn(labels, predictions)\n tf.contrib.summary.scalar('task_loss', tf.reduce_mean(task_loss))\n\n if self.auxiliary_loss_fn:\n aux_loss = self.auxiliary_loss_fn(state)\n tf.contrib.summary.scalar('aux_loss', aux_loss)\n else:\n aux_loss = tf.constant(0.0)\n\n # The PathNet optimizer uses the entry under `task_loss` as the target for\n # optimization, so that entry has to include all losses. The other entries\n # are there just for summaries.\n return {\n 'task_loss': task_loss + aux_loss,\n 'task_loss_without_aux_losses': task_loss\n }\n\n def zero_output(self, state):\n del state\n return {\n 'task_loss': tf.zeros([1]),\n 'task_loss_without_aux_losses': tf.zeros([1])\n }\n\n\nclass KerasComponent(object):\n \"\"\"Wraps a Keras network into a component that can be used with PathNet.\"\"\"\n\n def __init__(self, name, network, out_shape):\n \"\"\"Constructor.\n\n Args:\n name: (string) name for this component.\n network: keras network which is going to be wrapped.\n out_shape: expected output shape for `network` (excluding batch\n dimension) as a sequence of ints.\n \"\"\"\n\n self.name = name\n self.out_shape = out_shape\n self.network = network\n\n def __call__(self, state):\n x = state['in_tensor']\n training = state['training']\n\n x = self.network(x, training=training)\n\n return {'in_tensor': x}\n\n def zero_output(self, state):\n del state\n return {'in_tensor': tf.zeros([1] + self.out_shape)}\n\n\nclass IdentityComponent(KerasComponent):\n \"\"\"Component that implements an identity function.\"\"\"\n\n def __init__(self, out_shape):\n \"\"\"Constructor.\n\n Args:\n out_shape: shape for both input and output of this component.\n \"\"\"\n super(IdentityComponent, self).__init__(\n 'Identity', models.Sequential(), out_shape)\n\n def __call__(self, state):\n assert state['in_tensor'].shape[1:] == self.out_shape\n return super(IdentityComponent, self).__call__(state)\n\n\nclass FCLComponent(KerasComponent):\n \"\"\"Component that implements a fully connected neural network.\"\"\"\n\n def __init__(\n self, numbers_of_units, hidden_activation=None, out_activation=None):\n \"\"\"Constructor.\n\n Args:\n numbers_of_units: (list of int) number of hidden units for every layer\n (including the output layer)\n hidden_activation: activation function to apply after each hidden layer,\n ignored if there are no hidden layers.\n out_activation: activation function to apply at the output layer.\n \"\"\"\n\n num_layers = len(numbers_of_units)\n assert num_layers >= 1\n\n activations = [hidden_activation] * (num_layers - 1) + [out_activation]\n\n network = models.Sequential([\n layers.Dense(units, activation=activation)\n for units, activation in zip(numbers_of_units, activations)\n ])\n\n super(FCLComponent, self).__init__(\n '%sFCL' % num_layers, network, [numbers_of_units[-1]])\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"StructFormer and transformer model.\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom structformer import layers\n\n\ndef cumprod(x, reverse=False, exclusive=False):\n \"\"\"cumulative product.\"\"\"\n if reverse:\n x = x.flip([-1])\n\n if exclusive:\n x = F.pad(x[:, :, :-1], (1, 0), value=1)\n\n cx = x.cumprod(-1)\n\n if reverse:\n cx = cx.flip([-1])\n return cx\n\n\ndef cumsum(x, reverse=False, exclusive=False):\n \"\"\"cumulative sum.\"\"\"\n bsz, _, length = x.size()\n device = x.device\n if reverse:\n if exclusive:\n w = torch.ones([bsz, length, length], device=device).tril(-1)\n else:\n w = torch.ones([bsz, length, length], device=device).tril(0)\n cx = torch.bmm(x, w)\n else:\n if exclusive:\n w = torch.ones([bsz, length, length], device=device).triu(1)\n else:\n w = torch.ones([bsz, length, length], device=device).triu(0)\n cx = torch.bmm(x, w)\n return cx\n\n\ndef cummin(x, reverse=False, exclusive=False, max_value=1e9):\n \"\"\"cumulative min.\"\"\"\n if reverse:\n if exclusive:\n x = F.pad(x[:, :, 1:], (0, 1), value=max_value)\n x = x.flip([-1]).cummin(-1)[0].flip([-1])\n else:\n if exclusive:\n x = F.pad(x[:, :, :-1], (1, 0), value=max_value)\n x = x.cummin(-1)[0]\n return x\n\n\nclass Transformer(nn.Module):\n \"\"\"Transformer model.\"\"\"\n\n def __init__(self,\n hidden_size,\n nlayers,\n ntokens,\n nhead=8,\n dropout=0.1,\n dropatt=0.1,\n relative_bias=True,\n pos_emb=False,\n pad=0):\n \"\"\"Initialization.\n\n Args:\n hidden_size: dimension of inputs and hidden states\n nlayers: number of layers\n ntokens: number of output categories\n nhead: number of self-attention heads\n dropout: dropout rate\n dropatt: drop attention rate\n relative_bias: bool, indicate whether use a relative position based\n attention bias\n pos_emb: bool, indicate whether use a learnable positional embedding\n pad: pad token index\n \"\"\"\n\n super(Transformer, self).__init__()\n\n self.drop = nn.Dropout(dropout)\n\n self.emb = nn.Embedding(ntokens, hidden_size)\n if pos_emb:\n self.pos_emb = nn.Embedding(500, hidden_size)\n\n self.layers = nn.ModuleList([\n layers.TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout,\n dropatt=dropatt, relative_bias=relative_bias)\n for _ in range(nlayers)])\n\n self.norm = nn.LayerNorm(hidden_size)\n\n self.output_layer = nn.Linear(hidden_size, ntokens)\n self.output_layer.weight = self.emb.weight\n\n self.init_weights()\n\n self.nlayers = nlayers\n self.nhead = nhead\n self.ntokens = ntokens\n self.hidden_size = hidden_size\n self.pad = pad\n\n def init_weights(self):\n \"\"\"Initialize token embedding and output bias.\"\"\"\n initrange = 0.1\n self.emb.weight.data.uniform_(-initrange, initrange)\n if hasattr(self, 'pos_emb'):\n self.pos_emb.weight.data.uniform_(-initrange, initrange)\n self.output_layer.bias.data.fill_(0)\n\n def visibility(self, x, device):\n \"\"\"Mask pad tokens.\"\"\"\n visibility = (x != self.pad).float()\n visibility = visibility[:, None, :].expand(-1, x.size(1), -1)\n visibility = torch.repeat_interleave(visibility, self.nhead, dim=0)\n return visibility.log()\n\n def encode(self, x, pos):\n \"\"\"Standard transformer encode process.\"\"\"\n h = self.emb(x)\n if hasattr(self, 'pos_emb'):\n h = h + self.pos_emb(pos)\n h_list = []\n visibility = self.visibility(x, x.device)\n\n for i in range(self.nlayers):\n h_list.append(h)\n h = self.layers[i](\n h.transpose(0, 1), key_padding_mask=visibility).transpose(0, 1)\n\n output = h\n h_array = torch.stack(h_list, dim=2)\n\n return output, h_array\n\n def forward(self, x, pos):\n \"\"\"Pass the input through the encoder layer.\n\n Args:\n x: input tokens (required).\n pos: position for each token (optional).\n Returns:\n output: probability distributions for missing tokens.\n state_dict: parsing results and raw output\n \"\"\"\n\n batch_size, length = x.size()\n\n raw_output, _ = self.encode(x, pos)\n raw_output = self.norm(raw_output)\n raw_output = self.drop(raw_output)\n\n output = self.output_layer(raw_output)\n return output.view(batch_size * length, -1), {'raw_output': raw_output,}\n\n\nclass StructFormer(Transformer):\n \"\"\"StructFormer model.\"\"\"\n\n def __init__(self,\n hidden_size,\n nlayers,\n ntokens,\n nhead=8,\n dropout=0.1,\n dropatt=0.1,\n relative_bias=False,\n pos_emb=False,\n pad=0,\n n_parser_layers=4,\n conv_size=9,\n relations=('head', 'child'),\n weight_act='softmax'):\n \"\"\"Initialization.\n\n Args:\n hidden_size: dimension of inputs and hidden states\n nlayers: number of layers\n ntokens: number of output categories\n nhead: number of self-attention heads\n dropout: dropout rate\n dropatt: drop attention rate\n relative_bias: bool, indicate whether use a relative position based\n attention bias\n pos_emb: bool, indicate whether use a learnable positional embedding\n pad: pad token index\n n_parser_layers: number of parsing layers\n conv_size: convolution kernel size for parser\n relations: relations that are used to compute self attention\n weight_act: relations distribution activation function\n \"\"\"\n\n super(StructFormer, self).__init__(\n hidden_size,\n nlayers,\n ntokens,\n nhead=nhead,\n dropout=dropout,\n dropatt=dropatt,\n relative_bias=relative_bias,\n pos_emb=pos_emb,\n pad=pad)\n\n self.parser_layers = nn.ModuleList([\n nn.Sequential(layers.Conv1d(hidden_size, conv_size),\n nn.LayerNorm(hidden_size, elementwise_affine=False),\n nn.Tanh()) for i in range(n_parser_layers)])\n\n self.distance_ff = nn.Sequential(\n layers.Conv1d(hidden_size, 2),\n nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),\n nn.Linear(hidden_size, 1))\n\n self.height_ff = nn.Sequential(\n nn.Linear(hidden_size, hidden_size),\n nn.LayerNorm(hidden_size, elementwise_affine=False), nn.Tanh(),\n nn.Linear(hidden_size, 1))\n\n n_rel = len(relations)\n self._rel_weight = nn.Parameter(torch.zeros((nlayers, nhead, n_rel)))\n self._rel_weight.data.normal_(0, 0.1)\n\n self._scaler = nn.Parameter(torch.zeros(2))\n\n self.n_parse_layers = n_parser_layers\n self.weight_act = weight_act\n self.relations = relations\n\n @property\n def scaler(self):\n return self._scaler.exp()\n\n @property\n def rel_weight(self):\n if self.weight_act == 'sigmoid':\n return torch.sigmoid(self._rel_weight)\n elif self.weight_act == 'softmax':\n return torch.softmax(self._rel_weight, dim=-1)\n\n def parse(self, x, pos):\n \"\"\"Parse input sentence.\n\n Args:\n x: input tokens (required).\n pos: position for each token (optional).\n Returns:\n distance: syntactic distance\n height: syntactic height\n \"\"\"\n\n mask = (x != self.pad)\n mask_shifted = F.pad(mask[:, 1:], (0, 1), value=0)\n\n h = self.emb(x)\n for i in range(self.n_parse_layers):\n h = h.masked_fill(~mask[:, :, None], 0)\n h = self.parser_layers[i](h)\n\n height = self.height_ff(h).squeeze(-1)\n height.masked_fill_(~mask, -1e9)\n\n distance = self.distance_ff(h).squeeze(-1)\n distance.masked_fill_(~mask_shifted, 1e9)\n\n # Calbrating the distance and height to the same level\n length = distance.size(1)\n height_max = height[:, None, :].expand(-1, length, -1)\n height_max = torch.cummax(\n height_max.triu(0) - torch.ones_like(height_max).tril(-1) * 1e9,\n dim=-1)[0].triu(0)\n\n margin_left = torch.relu(\n F.pad(distance[:, :-1, None], (0, 0, 1, 0), value=1e9) - height_max)\n margin_right = torch.relu(distance[:, None, :] - height_max)\n margin = torch.where(margin_left > margin_right, margin_right,\n margin_left).triu(0)\n\n margin_mask = torch.stack([mask_shifted] + [mask] * (length - 1), dim=1)\n margin.masked_fill_(~margin_mask, 0)\n margin = margin.max()\n\n distance = distance - margin\n\n return distance, height\n\n def compute_block(self, distance, height):\n \"\"\"Compute constituents from distance and height.\"\"\"\n\n beta_logits = (distance[:, None, :] - height[:, :, None]) * self.scaler[0]\n\n gamma = torch.sigmoid(-beta_logits)\n ones = torch.ones_like(gamma)\n\n block_mask_left = cummin(\n gamma.tril(-1) + ones.triu(0), reverse=True, max_value=1)\n block_mask_left = block_mask_left - F.pad(\n block_mask_left[:, :, :-1], (1, 0), value=0)\n block_mask_left.tril_(0)\n\n block_mask_right = cummin(\n gamma.triu(0) + ones.tril(-1), exclusive=True, max_value=1)\n block_mask_right = block_mask_right - F.pad(\n block_mask_right[:, :, 1:], (0, 1), value=0)\n block_mask_right.triu_(0)\n\n block_p = block_mask_left[:, :, :, None] * block_mask_right[:, :, None, :]\n block = cumsum(block_mask_left).tril(0) + cumsum(\n block_mask_right, reverse=True).triu(1)\n\n return block_p, block\n\n def compute_head(self, height):\n \"\"\"Estimate head for each constituent.\"\"\"\n\n _, length = height.size()\n head_logits = height * self.scaler[1]\n index = torch.arange(length, device=height.device)\n\n mask = (index[:, None, None] <= index[None, None, :]) * (\n index[None, None, :] <= index[None, :, None])\n head_logits = head_logits[:, None, None, :].repeat(1, length, length, 1)\n head_logits.masked_fill_(~mask[None, :, :, :], -1e9)\n\n head_p = torch.softmax(head_logits, dim=-1)\n\n return head_p\n\n def generate_mask(self, x, distance, height):\n \"\"\"Compute head and cibling distribution for each token.\"\"\"\n\n bsz, length = x.size()\n\n eye = torch.eye(length, device=x.device, dtype=torch.bool)\n eye = eye[None, :, :].expand((bsz, -1, -1))\n\n block_p, block = self.compute_block(distance, height)\n head_p = self.compute_head(height)\n head = torch.einsum('blij,bijh->blh', block_p, head_p)\n head = head.masked_fill(eye, 0)\n child = head.transpose(1, 2)\n cibling = torch.bmm(head, child).masked_fill(eye, 0)\n\n rel_list = []\n if 'head' in self.relations:\n rel_list.append(head)\n if 'child' in self.relations:\n rel_list.append(child)\n if 'cibling' in self.relations:\n rel_list.append(cibling)\n\n rel = torch.stack(rel_list, dim=1)\n\n rel_weight = self.rel_weight\n\n dep = torch.einsum('lhr,brij->lbhij', rel_weight, rel)\n att_mask = dep.reshape(self.nlayers, bsz * self.nhead, length, length)\n\n return att_mask, cibling, head, block\n\n def encode(self, x, pos, att_mask):\n \"\"\"Structformer encoding process.\"\"\"\n\n visibility = self.visibility(x, x.device)\n h = self.emb(x)\n if hasattr(self, 'pos_emb'):\n assert pos.max() < 500\n h = h + self.pos_emb(pos)\n for i in range(self.nlayers):\n h = self.layers[i](\n h.transpose(0, 1), attn_mask=att_mask[i],\n key_padding_mask=visibility).transpose(0, 1)\n return h\n\n def forward(self, x, pos):\n \"\"\"Pass the input through the encoder layer.\n\n Args:\n x: input tokens (required).\n pos: position for each token (optional).\n Returns:\n output: probability distributions for missing tokens.\n state_dict: parsing results and raw output\n \"\"\"\n\n batch_size, length = x.size()\n\n distance, height = self.parse(x, pos)\n att_mask, cibling, head, block = self.generate_mask(x, distance, height)\n\n raw_output = self.encode(x, pos, att_mask)\n raw_output = self.norm(raw_output)\n raw_output = self.drop(raw_output)\n\n output = self.output_layer(raw_output)\n\n return output.view(batch_size * length, -1), \\\n {'raw_output': raw_output, 'distance': distance, 'height': height,\n 'cibling': cibling, 'head': head, 'block': block}\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Collapsed Amortized Variational Inference for SNLDS.\n\nThis is a reasonable baseline model for switching non-linear dynamical system\nwith the following architecture:\n1. an inference network, with Bidirectional-RNN for input embedding, and a\n forward RNN to get the posterior distribution of `q(z[1:T] | x[1:T])`.\n2. a continuous state transition network, `p(z[t] | z[t-1], s[t])`.\n3. a discrete state transition network that conditioned on the input,\n `p(s[t] | s[t-1], x[t-1])`.\n4. an emission network conditioned on the continuous hidden dynamics,\n `p(x[t] | z[t])`.\n\nIt also contains a function, `create_model()`, to help to create the SNLDS\nmodel discribed in ``Collapsed Amortized Variational Inference for Switching\nNonlinear Dynamical Systems``. 2019. https://arxiv.org/abs/1910.09588.\nAll the networks are configurable through function arguments `network_*`.\n\"\"\"\n\nimport collections\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nfrom snlds import model_base\nfrom snlds import utils\n\nnamedtuple = collections.namedtuple\n\nlayers = tf.keras.layers\ntfd = tfp.distributions\ntfpl = tfp.layers\n\nRANDOM_SEED = 131\n\n\ndef construct_initial_state_distribution(\n latent_dim,\n num_categ,\n use_trainable_cov=False,\n use_triangular_cov=False,\n raw_sigma_bias=0.0,\n sigma_min=1e-5,\n sigma_scale=0.05,\n dtype=tf.float32,\n name=\"z0\"):\n \"\"\"Construct the initial state distribution, `p(z[0])`.\n\n Args:\n latent_dim: an `int` scalar for dimension of continuous hidden states, `z`.\n num_categ: an `int` scalar for number of discrete states, `s`.\n use_trainable_cov: a `bool` scalar indicating whether the scale of `p(z[0])`\n is trainable. Default to False.\n use_triangular_cov: a `bool` scalar indicating whether to use triangular\n covariance matrices and `tfp.distributions.MultivariateNormalTriL` for\n distribution. Otherwise, a diagonal covariance matrices and\n `tfp.distributions.MultivariateNormalDiag` will be used.\n raw_sigma_bias: a `float` scalar to be added to the raw sigma, which is\n standard deviation of the distribution. Default to `0.`.\n sigma_min: a `float` scalar for minimal level of sigma to prevent\n underflow. Default to `1e-5`.\n sigma_scale: a `float` scalar for scaling the sigma. Default to `0.05`.\n The above three arguments are used as\n `sigma_scale * max(softmax(raw_sigma + raw_sigma_bias), sigma_min))`.\n dtype: data type for variables within the scope. Default to `tf.float32`.\n name: a `str` to construct names of variables.\n\n Returns:\n return_dist: a `tfp.distributions` instance for the initial state\n distribution, `p(z[0])`.\n \"\"\"\n\n glorot_initializer = tf.keras.initializers.GlorotUniform()\n z0_mean = tf.Variable(\n initial_value=glorot_initializer(shape=[num_categ, latent_dim],\n dtype=dtype),\n name=\"{}_mean\".format(name))\n\n if use_triangular_cov:\n z0_scale = tfp.math.fill_triangular(\n tf.Variable(\n initial_value=glorot_initializer(\n shape=[int(latent_dim * (latent_dim + 1) / 2)],\n dtype=dtype),\n name=\"{}_scale\".format(name),\n trainable=use_trainable_cov))\n z0_scale = (tf.maximum(tf.nn.softmax(z0_scale + raw_sigma_bias),\n sigma_min)\n * sigma_scale)\n return_dist = tfd.Independent(\n distribution=tfd.MultivariateNormalTriL(\n loc=z0_mean, scale_tril=z0_scale),\n reinterpreted_batch_ndims=0)\n\n else:\n z0_scale = tf.Variable(\n initial_value=glorot_initializer(\n shape=[latent_dim],\n dtype=dtype),\n name=\"{}_scale\".format(name),\n trainable=use_trainable_cov)\n z0_scale = (tf.maximum(tf.nn.softmax(z0_scale + raw_sigma_bias),\n sigma_min)\n * sigma_scale)\n return_dist = tfd.Independent(\n distribution=tfd.MultivariateNormalDiag(\n loc=z0_mean, scale_diag=z0_scale),\n reinterpreted_batch_ndims=0)\n\n return tfp.experimental.as_composite(return_dist)\n\n\nclass ContinuousStateTransition(tf.keras.Model):\n \"\"\"Transition for `p(z[t] | z[t-1], s[t])`.\"\"\"\n\n def __init__(self,\n transition_mean_networks,\n distribution_dim,\n num_categories=1,\n cov_mat=None,\n use_triangular_cov=False,\n use_trainable_cov=True,\n raw_sigma_bias=0.0,\n sigma_min=1e-5,\n sigma_scale=0.05,\n dtype=tf.float32,\n name=\"ContinuousStateTransition\"):\n \"\"\"Construct a `ContinuousStateTransition` instance.\n\n Args:\n transition_mean_networks: a list of `callable` networks, with the length\n of list same as `num_categories`. Each one of the networks will take\n previous step hidden state, `z[t-1]`, and returns the mean of\n transition distribution, `p(z[t] | z[t-1], s[t]=i)` for each\n discrete state `i`.\n distribution_dim: an `int` scalar for dimension of continuous hidden\n states, `z`.\n num_categories: an `int` scalar for number of discrete states, `s`.\n cov_mat: an optional `float` Tensor for predefined covariance matrix.\n Default to `None`, in which case, a `cov` variable will be created.\n use_triangular_cov: a `bool` scalar indicating whether to use triangular\n covariance matrices and `tfp.distributions.MultivariateNormalTriL` for\n distribution. Otherwise, a diagonal covariance matrices and\n `tfp.distributions.MultivariateNormalDiag` will be used.\n use_trainable_cov: a `bool` scalar indicating whether the scale of\n the distribution is trainable. Default to False.\n raw_sigma_bias: a `float` scalar to be added to the raw sigma, which is\n standard deviation of the distribution. Default to `0.`.\n sigma_min: a `float` scalar for minimal level of sigma to prevent\n underflow. Default to `1e-5`.\n sigma_scale: a `float` scalar for scaling the sigma. Default to `0.05`.\n The above three arguments are used as\n `sigma_scale * max(softmax(raw_sigma + raw_sigma_bias), sigma_min))`.\n dtype: data type for variables within the scope. Default to `tf.float32`.\n name: a `str` to construct names of variables.\n \"\"\"\n super(ContinuousStateTransition, self).__init__()\n\n assertion_str = (\n \"There has to be one transition mean networks for each discrete state\")\n assert len(transition_mean_networks) == num_categories, assertion_str\n self.z_trans_networks = transition_mean_networks\n self.num_categ = num_categories\n self.use_triangular_cov = use_triangular_cov\n self.distribution_dim = distribution_dim\n\n if cov_mat:\n self.cov_mat = cov_mat\n elif self.use_triangular_cov:\n self.cov_mat = tfp.math.fill_triangular(\n tf.Variable(\n tf.random.uniform(\n shape=[\n int(self.distribution_dim\n * (self.distribution_dim + 1) / 2)],\n minval=0., maxval=1.,\n dtype=dtype),\n name=\"{}_cov\".format(name),\n dtype=dtype,\n trainable=use_trainable_cov))\n self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias),\n sigma_min) * sigma_scale\n else:\n self.cov_mat = tf.Variable(\n tf.random.uniform(shape=[self.distribution_dim],\n minval=0.0, maxval=1.,\n dtype=dtype),\n name=\"{}_cov\".format(name),\n dtype=dtype,\n trainable=use_trainable_cov)\n self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias),\n sigma_min) * sigma_scale\n\n def call(self, input_tensor, dtype=tf.float32):\n\n input_tensor = tf.convert_to_tensor(input_tensor, dtype_hint=dtype)\n batch_size, num_steps, distribution_dim = tf.unstack(tf.shape(input_tensor))\n\n # The shape of the mean_tensor after tf.stack is [num_categ, batch_size,\n # num_steps, distribution_dim].,\n mean_tensor = tf.transpose(\n tf.stack([\n z_net(input_tensor) for z_net in self.z_trans_networks]),\n [1, 2, 0, 3])\n mean_tensor = tf.reshape(mean_tensor,\n [batch_size, num_steps,\n self.num_categ, distribution_dim])\n\n if self.use_triangular_cov:\n output_dist = tfd.MultivariateNormalTriL(\n loc=mean_tensor,\n scale_tril=self.cov_mat)\n else:\n output_dist = tfd.MultivariateNormalDiag(\n loc=mean_tensor,\n scale_diag=self.cov_mat)\n\n return tfp.experimental.as_composite(output_dist)\n\n @property\n def output_event_dims(self):\n return self.distribution_dim\n\n\nclass DiscreteStateTransition(tf.keras.Model):\n \"\"\"Discrete state transition p(s[t] | s[t-1], x[t-1]).\"\"\"\n\n def __init__(self,\n transition_network,\n num_categories):\n \"\"\"Construct a `DiscreteStateTransition` instance.\n\n Args:\n transition_network: a `callable` network taking batch conditional inputs,\n `x[t-1]`, and returning the discrete state transition matrices,\n `log p(s[t] |s[t-1], x[t-1])`.\n num_categories: an `int` scalar for number of discrete states, `s`.\n \"\"\"\n super(DiscreteStateTransition, self).__init__()\n self.dense_net = transition_network\n self.num_categ = num_categories\n\n def call(self, input_tensor, dtype=tf.float32):\n\n input_tensor = tf.convert_to_tensor(input_tensor, dtype_hint=dtype)\n batch_size, num_steps = tf.unstack(tf.shape(input_tensor)[:2])\n transition_tensor = self.dense_net(input_tensor)\n transition_tensor = tf.reshape(\n transition_tensor,\n [batch_size, num_steps, self.num_categ, self.num_categ])\n return transition_tensor\n\n @property\n def output_event_dims(self):\n return self.num_categ\n\n\nclass GaussianDistributionFromMean(tf.keras.Model):\n \"\"\"Emission model p(x[t] | z[t]).\"\"\"\n\n def __init__(self,\n emission_mean_network,\n observation_dim,\n cov_mat=None,\n use_triangular_cov=False,\n use_trainable_cov=True,\n raw_sigma_bias=0.0,\n sigma_min=1e-5,\n sigma_scale=0.05,\n dtype=tf.float32,\n name=\"GaussianDistributionFromMean\"):\n \"\"\"Construct a `GaussianDistributionFromMean` instance.\n\n Args:\n emission_mean_network: a `callable` network taking continuous hidden\n states, `z[t]`, and returning the mean of emission distribution,\n `p(x[t] | z[t])`.\n observation_dim: an `int` scalar for dimension of observations, `x`.\n cov_mat: an optional `float` Tensor for predefined covariance matrix.\n Default to `None`, in which case, a `cov` variable will be created.\n use_triangular_cov: a `bool` scalar indicating whether to use triangular\n covariance matrices and `tfp.distributions.MultivariateNormalTriL` for\n distribution. Otherwise, a diagonal covariance matrices and\n `tfp.distributions.MultivariateNormalDiag` will be used.\n use_trainable_cov: a `bool` scalar indicating whether the scale of\n the distribution is trainable. Default to False.\n raw_sigma_bias: a `float` scalar to be added to the raw sigma, which is\n standard deviation of the distribution. Default to `0.`.\n sigma_min: a `float` scalar for minimal level of sigma to prevent\n underflow. Default to `1e-5`.\n sigma_scale: a `float` scalar for scaling the sigma. Default to `0.05`.\n The above three arguments are used as\n `sigma_scale * max(softmax(raw_sigma + raw_sigma_bias), sigma_min))`.\n dtype: data type for variables within the scope. Default to `tf.float32`.\n name: a `str` to construct names of variables.\n \"\"\"\n super(GaussianDistributionFromMean, self).__init__()\n self.observation_dim = observation_dim\n self.x_emission_net = emission_mean_network\n self.use_triangular_cov = use_triangular_cov\n\n if cov_mat:\n self.cov_mat = cov_mat\n elif self.use_triangular_cov:\n local_variable = tf.Variable(\n tf.random.uniform(\n shape=[int(self.observation_dim*(self.observation_dim+1)/2)],\n minval=0., maxval=1.,\n dtype=dtype),\n name=\"{}_cov\".format(name),\n dtype=dtype,\n trainable=use_trainable_cov)\n self.cov_mat = tfp.math.fill_triangular(\n local_variable)\n self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias),\n sigma_min) * sigma_scale\n else:\n self.cov_mat = tf.Variable(\n initial_value=tf.random.uniform(shape=[self.observation_dim],\n minval=0.0, maxval=1.,\n dtype=dtype),\n name=\"{}_cov\".format(name),\n dtype=dtype,\n trainable=use_trainable_cov)\n self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias),\n sigma_min) * sigma_scale\n\n def call(self, input_tensor, dtype=tf.float32):\n\n input_tensor = tf.convert_to_tensor(input_tensor, dtype_hint=dtype)\n\n mean_tensor = self.x_emission_net(input_tensor)\n\n if self.use_triangular_cov:\n output_dist = tfd.MultivariateNormalTriL(\n loc=mean_tensor,\n scale_tril=self.cov_mat)\n else:\n output_dist = tfd.MultivariateNormalDiag(\n loc=mean_tensor,\n scale_diag=self.cov_mat)\n\n return tfp.experimental.as_composite(output_dist)\n\n @property\n def output_event_dims(self):\n return self.observation_dim\n\n\nclass RnnInferenceNetwork(tf.keras.Model):\n \"\"\"Inference network for posterior q(z[1:T] | x[1:T]).\"\"\"\n\n def __init__(self,\n posterior_rnn,\n posterior_dist,\n latent_dim,\n embedding_network=None):\n \"\"\"Construct a `RnnInferenceNetwork` instance.\n\n Args:\n posterior_rnn: a RNN cell, `h[t]=f_RNN(h[t-1], z[t-1], input[t])`,\n which recursively takes previous step RNN states `h`, previous step\n sampled dynamical state `z[t-1]`, and conditioned input `input[t]`.\n posterior_dist: a distribution instance for `p(z[t] | h[t])`,\n where h[t] is the output of `posterior_rnn`.\n latent_dim: an `int` scalar for dimension of continuous hidden\n states, `z`.\n embedding_network: an optional network to embed the observations, `x[t]`.\n Default to `None`, in which case, no embedding is applied.\n \"\"\"\n super(RnnInferenceNetwork, self).__init__()\n self.latent_dim = latent_dim\n self.posterior_rnn = posterior_rnn\n self.posterior_dist = posterior_dist\n\n if embedding_network is None:\n self.embedding_network = lambda x: x\n self.embedding_network = embedding_network\n\n def call(self,\n inputs,\n num_samples=1,\n dtype=tf.float32,\n random_seed=RANDOM_SEED,\n parallel_iterations=10):\n \"\"\"Recursively sample z[t] ~ q(z[t]|h[t]=f_RNN(h[t-1], z[t-1], h[t]^b)).\n\n Args:\n inputs: a float `Tensor` of size [batch_size, num_steps, obs_dim], where\n each observation should be flattened.\n num_samples: an `int` scalar for number of samples per time-step, for\n posterior inference networks, `z[i] ~ q(z[1:T] | x[1:T])`.\n dtype: The data type of input data.\n random_seed: an `Int` as the seed for random number generator.\n parallel_iterations: a positive `Int` indicates the number of iterations\n allowed to run in parallel in `tf.while_loop`, where `tf.while_loop`\n defaults it to be 10.\n\n Returns:\n sampled_z: a float 3-D `Tensor` of size [num_samples, batch_size,\n num_steps, latent_dim], which stores the z_t sampled from posterior.\n entropies: a float 2-D `Tensor` of size [num_samples, batch_size,\n num_steps], which stores the entropies of posterior distributions.\n log_probs: a float 2-D `Tensor` of size [num_samples. batch_size,\n num_steps], which stores the log posterior probabilities.\n \"\"\"\n inputs = tf.convert_to_tensor(inputs, dtype_hint=dtype)\n batch_size, num_steps = tf.unstack(tf.shape(inputs)[:2])\n latent_dim = self.latent_dim\n\n ## passing through embedding_network, e.g. bidirectional RNN\n inputs = self.embedding_network(inputs)\n\n ## passing through forward RNN\n ta_names = [\"rnn_states\", \"latent_states\", \"entropies\", \"log_probs\"]\n tas = [tf.TensorArray(tf.float32, num_steps, name=n) for n in ta_names]\n\n t0 = tf.constant(0, tf.int32)\n loopstate = namedtuple(\"LoopState\", \"rnn_state latent_encoded\")\n\n initial_rnn_state = self.posterior_rnn.get_initial_state(\n batch_size=batch_size * num_samples,\n dtype=dtype)\n if (isinstance(self.posterior_rnn, layers.GRUCell)\n or isinstance(self.posterior_rnn, layers.SimpleRNNCell)):\n initial_rnn_state = [initial_rnn_state]\n\n init_state = (t0,\n loopstate(\n rnn_state=initial_rnn_state,\n latent_encoded=tf.zeros(\n [batch_size * num_samples, latent_dim],\n dtype=tf.float32)), tas)\n\n def _cond(t, *unused_args):\n return t < num_steps\n\n def _step(t, loop_state, tas):\n \"\"\"One step in tf.while_loop.\"\"\"\n prev_latent_state = loop_state.latent_encoded\n prev_rnn_state = loop_state.rnn_state\n current_input = inputs[:, t, :]\n\n # Duplicate current observation to sample multiple trajectories.\n current_input = tf.tile(current_input, [num_samples, 1])\n\n rnn_input = tf.concat([current_input, prev_latent_state],\n axis=-1) # num_samples * BS, latent_dim+input_dim\n rnn_out, rnn_state = self.posterior_rnn(\n inputs=rnn_input,\n states=prev_rnn_state)\n dist = self.posterior_dist(rnn_out)\n latent_state = dist.sample(seed=random_seed)\n\n ## rnn_state is a list of [batch_size, rnn_hidden_dim],\n ## after TA.stack(), the dimension will be\n ## [num_steps, 1 for GRU/2 for LSTM, batch, rnn_dim]\n tas_updates = [rnn_state,\n latent_state,\n dist.entropy(),\n dist.log_prob(latent_state)]\n tas = utils.write_updates_to_tas(tas, t, tas_updates)\n\n return (t+1,\n loopstate(rnn_state=rnn_state,\n latent_encoded=latent_state),\n tas)\n ## end of _step function\n\n _, _, tas_final = tf.while_loop(\n _cond, _step, init_state, parallel_iterations=parallel_iterations)\n\n sampled_z, entropies, log_probs = [\n utils.tensor_for_ta(ta, swap_batch_time=True) for ta in tas_final[1:]\n ]\n\n sampled_z = tf.reshape(sampled_z,\n [num_samples, batch_size, num_steps, latent_dim])\n entropies = tf.reshape(entropies, [num_samples, batch_size, num_steps])\n log_probs = tf.reshape(log_probs, [num_samples, batch_size, num_steps])\n return sampled_z, entropies, log_probs\n\n\ndef create_model(num_categ,\n hidden_dim,\n observation_dim,\n config_emission,\n config_inference,\n config_z_initial,\n config_z_transition,\n network_emission,\n network_input_embedding,\n network_posterior_rnn,\n network_s_transition,\n networks_z_transition,\n network_posterior_mlp=lambda x: x,\n name=\"snlds\"):\n \"\"\"Construct SNLDS model.\n\n Args:\n num_categ: an `int` scalar for number of discrete states, `s`.\n hidden_dim: an `int` scalar for dimension of continuous hidden states, `z`.\n observation_dim: an `int` scalar for dimension of observations, `x`.\n config_emission: a `dict` for configuring emission distribution,\n `p(x[t] | z[t])`.\n config_inference: a `dict` for configuring the posterior distribution,\n `q(z[t]|h[t]=f_RNN(h[t-1], z[t-1], h[t]^b))`.\n config_z_initial: a `dict` for configuring the initial distribution of\n continuous hidden state, `p(z[0])`.\n config_z_transition: a `dict` for configuring the transition distribution\n `p(z[t] | z[t-1], s[t])`.\n network_emission: a `callable` network taking continuous hidden\n states, `z[t]`, and returning the mean of emission distribution,\n `p(x[t] | z[t])`.\n network_input_embedding: a `callable` network to embed the observations,\n `x[t]`. E.g. a bidirectional RNN to embedding `x[1:T]`.\n network_posterior_rnn: a RNN cell, `h[t]=f_RNN(h[t-1], z[t-1], input[t])`,\n which recursively takes previous step RNN states `h`, previous step\n sampled dynamical state `z[t-1]`, and conditioned input `input[t]`.\n network_s_transition: a `callable` network taking batch conditional inputs,\n `x[t-1]`, and returning the discrete state transition matrices,\n `log p(s[t] |s[t-1], x[t-1])`.\n networks_z_transition: a list of `callable` networks, with the length\n of list same as `num_categories`. Each one of the networks will take\n previous step hidden state, `z[t-1]`, and returns the mean of\n transition distribution, `p(z[t] | z[t-1], s[t]=i)` for each\n discrete state `i`.\n network_posterior_mlp: an optional network to embedding the output of\n inference RNN networks, before passing into the distribution as mean,\n `q(z[t] | mlp( h[t] ))`. Default to identity mapping.\n name: a `str` to construct names of variables.\n\n Returns:\n An instance of instantiated `model_base.SwitchingNLDS` model.\n \"\"\"\n\n z_transition = ContinuousStateTransition(\n transition_mean_networks=networks_z_transition,\n distribution_dim=hidden_dim,\n num_categories=num_categ,\n cov_mat=config_z_transition.cov_mat,\n use_triangular_cov=config_z_transition.use_triangular_cov,\n use_trainable_cov=config_z_transition.use_trainable_cov,\n raw_sigma_bias=config_z_transition.raw_sigma_bias,\n sigma_min=config_z_transition.sigma_min,\n sigma_scale=config_z_transition.sigma_scale,\n name=name+\"_z_trans\")\n\n s_transition = DiscreteStateTransition(\n transition_network=network_s_transition,\n num_categories=num_categ)\n\n emission_network = GaussianDistributionFromMean(\n emission_mean_network=network_emission,\n observation_dim=observation_dim,\n cov_mat=config_emission.cov_mat,\n use_triangular_cov=config_emission.use_triangular_cov,\n use_trainable_cov=config_emission.use_trainable_cov,\n raw_sigma_bias=config_emission.raw_sigma_bias,\n sigma_min=config_emission.sigma_min,\n sigma_scale=config_emission.sigma_scale,\n name=name+\"_x_emit\")\n\n posterior_distribution = GaussianDistributionFromMean(\n emission_mean_network=network_posterior_mlp,\n observation_dim=hidden_dim,\n cov_mat=config_inference.cov_mat,\n use_triangular_cov=config_inference.use_triangular_cov,\n use_trainable_cov=config_inference.use_trainable_cov,\n raw_sigma_bias=config_inference.raw_sigma_bias,\n sigma_min=config_inference.sigma_min,\n sigma_scale=config_inference.sigma_scale,\n name=name+\"_posterior\")\n\n posterior_network = RnnInferenceNetwork(\n posterior_rnn=network_posterior_rnn,\n posterior_dist=posterior_distribution,\n latent_dim=hidden_dim,\n embedding_network=network_input_embedding)\n\n z_initial_distribution = construct_initial_state_distribution(\n latent_dim=hidden_dim,\n num_categ=num_categ,\n use_trainable_cov=config_z_initial.use_trainable_cov,\n use_triangular_cov=config_z_initial.use_triangular_cov,\n raw_sigma_bias=config_z_initial.raw_sigma_bias,\n sigma_min=config_z_initial.sigma_min,\n sigma_scale=config_z_initial.sigma_scale,\n name=\"init_dist\")\n\n snlds_model = model_base.SwitchingNLDS(\n continuous_transition_network=z_transition,\n discrete_transition_network=s_transition,\n emission_network=emission_network,\n inference_network=posterior_network,\n initial_distribution=z_initial_distribution,\n continuous_state_dim=None,\n num_categories=None,\n discrete_state_prior=None)\n\n return snlds_model\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Test for RandomStretchSqueeze data augmentation.\"\"\"\nimport numpy as np\nfrom kws_streaming.layers import random_stretch_squeeze\nfrom kws_streaming.layers import test_utils\nfrom kws_streaming.layers.compat import tf\nfrom kws_streaming.layers.compat import tf1\ntf1.disable_eager_execution()\n\n\nclass RandomStretchSqueezeTest(tf.test.TestCase):\n\n def setUp(self):\n super(RandomStretchSqueezeTest, self).setUp()\n self.input_shape = [2, 7] # [batch, audio_sequence]\n self.seed = 5\n\n def test_random_stretch_squeeze(self):\n test_utils.set_seed(self.seed)\n audio = np.zeros(self.input_shape)\n audio[:, 2:5,] = 1\n inputs = tf.keras.layers.Input(\n shape=self.input_shape[1:],\n batch_size=self.input_shape[0],\n dtype=tf.float32)\n outputs = random_stretch_squeeze.RandomStretchSqueeze(\n resample_offset=0.5,\n seed=self.seed)(\n inputs, training=True)\n model = tf.keras.models.Model(inputs, outputs)\n prediction = model.predict(audio)\n\n # confirm that data are squeezed\n target0 = np.array([0., 0., 1., 1., 0., 0., 0.])\n self.assertAllClose(prediction[0, :], target0)\n\n # confirm that data are stretched\n target1 = np.array([0., 0.44444, 1., 1., 1., 0.44444, 0.])\n self.assertAllClose(prediction[1, :], target1, atol=1e-4)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utilities for reading images, parsing protobufs, etc.\"\"\"\n\nimport math\nimport os\nimport random\n\nfrom google.protobuf import text_format\nimport matplotlib as plt\nimport matplotlib.cm # pylint: disable=unused-import\nimport numpy as np\nfrom skimage.draw import ellipse\nfrom skimage.exposure import adjust_gamma\nfrom skimage.filters import gaussian\nfrom skimage.transform import ProjectiveTransform\nfrom skimage.transform import resize\nfrom skimage.transform import warp\nimport tensorflow as tf\nimport yaml\n\nfrom keypose import data_pb2 as pb\n\ntry:\n import cv2 # pylint: disable=g-import-not-at-top\nexcept ImportError as e:\n print(e)\n\n# Top level keypose directory.\nKEYPOSE_PATH = os.path.join(os.getcwd(), 'keypose')\n\n\n# Read image, including .exr images.\ndef read_image(fname):\n ext = os.path.splitext(fname)[1]\n if ext == '.exr':\n print('reading exr file')\n image = cv2.imread(fname, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)\n else:\n image = cv2.imread(fname)\n assert image is not None, 'Cannot open %s' % fname\n return image\n\n\n# Camera array to camera protobuf\ndef cam_array_to_pb(cam):\n cam_pb = pb.Camera()\n cam_pb.fx = cam[0]\n cam_pb.fy = cam[1]\n cam_pb.cx = cam[2]\n cam_pb.cy = cam[3]\n cam_pb.baseline = cam[4]\n cam_pb.resx = cam[5]\n cam_pb.resy = cam[6]\n return cam_pb\n\n\n# Camera protobuf to camera array\ndef cam_pb_to_array(cam_pb):\n return [\n cam_pb.fx, cam_pb.fy, cam_pb.cx, cam_pb.cy, cam_pb.baseline, cam_pb.resx,\n cam_pb.resy\n ]\n\n\n# Dummy transform that always produces 0 vector as result.\ndef dummy_to_uvd():\n to_uvd = np.zeros((4, 4))\n to_uvd[3, 3] = 1.0\n return to_uvd\n\n\n# Zero uvd stack.\ndef dummy_keys_uvd(num):\n uvd = np.zeros(4)\n uvd[3] = 1.0\n return [uvd for _ in range(num)]\n\n\ndef k_matrix_from_camera(camera):\n return np.array([\n [camera.fx, 0, camera.cx], # fx, cx\n [0, camera.fy, camera.cy], # fy, cy\n [0, 0, 1]\n ])\n\n\ndef q_matrix_from_camera(camera):\n return np.array([\n [1.0, 0, 0, -camera.cx], # cx\n [0, 1.0, 0, -camera.cy], # cy\n [0, 0, 0, camera.fx], # fx\n [0, 0, 1.0 / camera.baseline, 0]\n ]) # baseline\n\n\ndef p_matrix_from_camera(camera):\n return np.array([\n [camera.fx, 0, camera.cx, 0], # fx, cx\n [0, camera.fy, camera.cy, 0], # fy, cy\n [0, 0, 0, camera.fx * camera.baseline], # fx*baseline\n [0, 0, 1.0, 0]\n ])\n\n\n# Parse a transform protobuf.\ndef get_transform(trans_pb):\n transform = np.array(trans_pb.element)\n if transform.size == 16:\n return transform.reshape((4, 4))\n return None\n\n\ndef get_keypoints(targ_pb):\n \"\"\"Parse a keypoint protobuf.\"\"\"\n uvds = []\n visible = []\n focal_length = targ_pb.camera.fx\n baseline = targ_pb.camera.baseline\n for kp_pb in targ_pb.keypoints:\n uvds.append(\n np.array([kp_pb.u, kp_pb.v, focal_length * baseline / kp_pb.z, 1]))\n visible.append(kp_pb.visible)\n transform = get_transform(targ_pb.transform)\n if transform is None:\n world_t_uvd = None\n else:\n world_t_uvd = np.linalg.inv(transform).dot(\n q_matrix_from_camera(targ_pb.camera))\n return np.array(uvds), world_t_uvd, np.array(visible)\n\n\n# NOTE: xyzs are NOT world coords. xy are percent image coords, z is depth (m).\ndef get_contents_pb(targ_pb):\n uvds, xyzs, visible = get_keypoints(targ_pb)\n cam = targ_pb.camera\n transform = get_transform(targ_pb.transform)\n if transform is None:\n return cam, None, None, uvds, xyzs, visible, transform\n uvd_t_world = p_matrix_from_camera(cam).dot(transform)\n world_t_uvd = np.linalg.inv(transform).dot(q_matrix_from_camera(cam))\n return cam, uvd_t_world, world_t_uvd, uvds, xyzs, visible, transform\n\n\n# Reading text-formatted protobuf files\ndef read_from_text_file(path, proto):\n with open(path, 'r') as file:\n text_format.Parse(file.read(), proto)\n return proto\n\n\ndef read_target_pb(path):\n target_pb = pb.KeyTargets()\n read_from_text_file(path, target_pb)\n return target_pb\n\n\ndef read_keys_pb(path):\n target_pb = pb.KeyTargets()\n read_from_text_file(path, target_pb)\n return target_pb.kp_target\n\n\n# Returns a dict of the filename strings in a TfSet.\ndef read_tfset(path):\n data_pb = pb.TfSet()\n read_from_text_file(path, data_pb)\n return data_pb\n\n\ndef make_tfset(train_names, val_names, name):\n tfset_pb = pb.TfSet()\n tfset_pb.train[:] = train_names\n tfset_pb.val[:] = val_names\n tfset_pb.name = name\n return tfset_pb\n\n\n# Read the contents of a target protobuf.\ndef read_contents_pb(path):\n return get_contents_pb(read_target_pb(path).kp_target)\n\n\n# Make a DataParams protobuf.\ndef make_data_params(resx, resy, num_kp, cam):\n data_pb = pb.DataParams()\n data_pb.camera.CopyFrom(cam)\n data_pb.resx = resx\n data_pb.resy = resy\n data_pb.num_kp = num_kp\n return data_pb\n\n\n# Read contents of a camera protobuf.\ndef read_data_params(path):\n data_pb = pb.DataParams()\n read_from_text_file(path, data_pb)\n cam = data_pb.camera\n return data_pb.resx, data_pb.resy, data_pb.num_kp, cam\n\n\ndef write_to_text_file(path, proto):\n with open(path, 'w') as file:\n file.write(str(proto))\n\n\ndef project_np(mat, vec):\n \"\"\"Projects homogeneous 3D XYZ coordinates to image uvd coordinates.\"\"\"\n # <vec> has shape [4, N].\n # <mat> has shape [4, 4]\n # Return has shape [4, N].\n\n p = mat.dot(vec)\n # Using <3:4> instead of <3> preserves shape.\n p = p / (p[3:4, :] + 1.0e-10)\n return p\n\n\n# Maximum number of projection frames for losses.\nMAX_TARGET_FRAMES = 5\n\n# Standard image input parameters for the model.\nDEFAULT_PARAMS = \"\"\"\nbatch_size: 32\ndset_dir: ''\nmodel_dir: ''\nsteps: 80000\n\nmodel_params:\nmodel_params:\n use_regress: True # Use regression or integration.\n batchnorm: [0.999, 1.0e-8, False]\n num_filters: 48 # Number of filters across DCNN.\n filter_size: 3\n max_dilation: 32\n dilation_rep: 1\n dropout: 0.0\n disp_default: 30\n sym: [0]\n input_sym: [0] # Mix up symmetric ground truth values.\n use_stereo: true\n visible: true # Use only samples with visible keypoints.\n\n crop: [180, 120, 30] # Crop patch size, WxH, plus disp offset.\n dither: 20.0 # Amount to dither the crop, in pixels.\n\n loss_kp: 1.0\n loss_kp_step: [0, 200]\n loss_prob: 0.001\n loss_proj: 2.5\n loss_proj_step: [10000, 20000]\n loss_reg: 0.01\n loss_dispmap: 1.0\n loss_dispmap_step: [5000, 10000]\n\n noise: 4.0\n occ_fraction: 0.2\n kp_occ_radius: 0.0 # Radius for occlusion for real-world keypoints.\n blur: [1.0, 4.0] # Min, max in pixels.\n motion: [0, 0, 0, 0] # Motion blur, min/max in pixels, min/max in angle (deg).\n gamma: [0.8, 1.2]\n\n rot: [0.0, 0.0, 0.0] # In degrees, [X-axis, Y-axis, Z-axis]\n\n # Homography parameters [X-axis, Y-axis]\n shear: [] # Use X-axis only for stereo [10,0].\n scale: [] # [min, max] applied only on the Y axis.\n flip: [] # Use Y-axis only for stereo [False,True].\n\"\"\"\n\n\ndef get_params(param_file=None,\n cam_file=None,\n cam_image_file=None,\n defaults=DEFAULT_PARAMS):\n \"\"\"Returns default or overridden user-specified parameters, and cam params.\"\"\"\n\n # param_file points to a yaml string.\n # cam_file points to a camera pbtxt.\n # cam_image_file points to a camera pbtxt.\n\n params = ConfigParams(defaults)\n if param_file:\n params.merge_yaml(param_file)\n mparams = params.model_params\n\n cam = None\n if cam_file:\n print('Model camera params file name is: %s' % cam_file)\n resx, resy, num_kp, cam = read_data_params(cam_file)\n\n mparams.resx = resx\n mparams.resy = resy\n mparams.num_kp = num_kp\n mparams.modelx = resx\n mparams.modely = resy\n mparams.disp_default /= mparams.resx # Convert to fraction of image.\n\n if mparams.crop:\n mparams.modelx = int(mparams.crop[0])\n mparams.modely = int(mparams.crop[1])\n\n cam_image = None\n if cam_image_file:\n print('Image camera params file name is: %s' % cam_image_file)\n _, _, _, cam_image = read_data_params(cam_image_file)\n\n print('MParams:', mparams.make_dict())\n return params, cam, cam_image\n\n\n# General configuration class for referencing parameters using dot notation.\nclass ConfigParams:\n \"\"\"General configuration class for referencing params using dot notation.\"\"\"\n\n def __init__(self, init=None):\n if init:\n self.merge_yaml(init)\n\n def make_dict(self):\n ret = {}\n for k in self.__dict__:\n val = self.__dict__[k]\n if isinstance(val, self.__class__):\n ret[k] = val.make_dict()\n else:\n ret[k] = val\n return ret\n\n # No nesting.\n def make_shallow_dict(self):\n ret = {}\n for k in self.__dict__:\n val = self.__dict__[k]\n if not isinstance(val, self.__class__):\n ret[k] = val\n return ret\n\n def read_yaml(self, fname):\n with open(fname, 'r') as f:\n ret = self.merge_yaml(f)\n return ret\n\n def write_yaml(self, fname):\n with open(fname, 'w') as f:\n yaml.dump(self.make_dict(), f, default_flow_style=None)\n\n def merge_dict(self, p_dict):\n \"\"\"Merges a dictionary into this params.\"\"\"\n for k in p_dict:\n val = p_dict[k]\n if k == 'default_file':\n print('Default file:', val)\n fname = os.path.join(KEYPOSE_PATH, val + '.yaml')\n print('Default file fname:', fname)\n self.read_yaml(fname)\n continue\n if isinstance(val, dict):\n if getattr(self, k, None):\n sub_params = getattr(self, k)\n sub_params.merge_dict(val)\n else:\n sub_params = self.__class__()\n sub_params.merge_dict(val)\n setattr(self, k, sub_params)\n else:\n setattr(self, k, val)\n\n def merge_yaml(self, yaml_str):\n try:\n ret = yaml.safe_load(yaml_str)\n except yaml.YAMLError as exc:\n print('Error in loading yaml string')\n print(exc)\n return False\n self.merge_dict(ret)\n return True\n\n # Takes a string of the form 'a:1,b:2,c:[1,2],d:abcd', etc.\n # No nesting.\n def merge_str(self, p_str):\n items = p_str.split('=')\n assert len(items) >= 2\n # pylint: disable=g-complex-comprehension\n items = items[:1] + [\n item for v in items[1:-1] for item in v.rsplit(',', 1)\n ] + items[-1:]\n y_list = [items[i] + ': ' + items[i + 1] for i in range(0, len(items), 2)]\n y_str = '\\n'.join(y_list)\n self.merge_yaml(y_str)\n\n # Returns a string suitable for reading back in. Does not allow\n # nested ConfigParams.\n def __repr__(self):\n # Checks float repr for not having a decimal point in scientific notation.\n # Checks for None and returns empty string.\n def yaml_str(obj):\n if isinstance(obj, type(None)):\n return ''\n if isinstance(obj, list):\n return '[' + ','.join([yaml_str(x) for x in obj]) + ']'\n ret = str(obj)\n if isinstance(obj, float):\n if 'e' in ret and '.' not in ret:\n return '.0e'.join(ret.split('e'))\n return ret\n\n ivars = self.make_shallow_dict()\n s = ','.join([k + '=' + yaml_str(ivars[k]) for k in ivars])\n return s.replace(' ', '')\n\n\n# uint8 image [0,255] to float [0,1]\ndef image_uint8_to_float(image):\n if image.dtype == np.float32:\n return image\n image = image.astype(np.float32) * (1.0 / 255.0)\n image_np = np.clip(image, 0.0, 1.0)\n return image_np\n\n\ndef resize_image(image, cam, cam_image, targs_pb):\n \"\"\"Resize an image using scaling and cropping; changes kps_pb to correspond.\"\"\"\n resx, resy = int(cam_image.resx), int(cam_image.resy)\n nxs, nys = int(cam.resx), int(cam.resy)\n fx = cam_image.fx\n nfx = cam.fx\n scale = fx / nfx\n\n crop = resy - nys * scale, resx - nxs * scale\n cropx, cropy = 0, 0\n if crop[0] > 1.5:\n cropy = int(round(crop[0] * 0.5))\n if crop[1] > 1.5:\n cropx = int(round(crop[1] * 0.5))\n\n # Resize image.\n image = image[cropy:resy - cropy, cropx:resx - cropx, :]\n image = resize(image, (nys, nxs), mode='constant') # Converts to float.\n image = image.astype(np.float32)\n\n def scale_cam(cam_pb):\n cam_pb.fx /= scale\n cam_pb.fy /= scale\n cam_pb.cx = (cam_pb.cx - cropx) / scale\n cam_pb.cy = (cam_pb.cy - cropy) / scale\n cam_pb.resx = nxs\n cam_pb.resy = nys\n\n def resize_target(targ_pb):\n scale_cam(targ_pb.camera)\n for kp in targ_pb.keypoints:\n kp.u = (kp.u - cropx) / scale\n kp.v = (kp.v - cropy) / scale\n kp.x = kp.u / nxs\n kp.y = kp.v / nys\n if kp.u < 0 or kp.u >= nxs or kp.v < 0 or kp.v >= nys:\n kp.visible = 0.0\n\n resize_target(targs_pb.kp_target)\n for targ_pb in targs_pb.proj_targets:\n resize_target(targ_pb)\n\n return image\n\n\ndef rotation_transform(x_rot, y_rot, z_rot):\n \"\"\"Creates a rotation transform with rotations around the three axes.\n\n Args:\n x_rot: rotate around X axis (degrees).\n y_rot: rotate around Y axis (degrees).\n z_rot: rotate around Z axis (degrees).\n\n Returns:\n 4x4 transform.\n \"\"\"\n x_rot = np.pi * x_rot / 180.0\n xt = np.array([[1.0, 0, 0, 0], [0, np.cos(x_rot), -np.sin(x_rot), 0.0],\n [0, np.sin(x_rot), np.cos(x_rot), 0.0], [0, 0, 0, 1]])\n y_rot = np.pi * y_rot / 180.0\n yt = np.array([[np.cos(y_rot), 0, np.sin(y_rot), 0], [0, 1, 0, 0],\n [-np.sin(y_rot), 0, np.cos(y_rot), 0], [0, 0, 0, 1]])\n z_rot = np.pi * z_rot / 180.0\n zt = np.array([[np.cos(z_rot), -np.sin(z_rot), 0, 0],\n [np.sin(z_rot), np.cos(z_rot), 0, 0], [0, 0, 1, 0],\n [0, 0, 0, 1]])\n return xt.dot(yt).dot(zt)\n\n\n# rotation of the camera\ndef rotate_camera(rotation, image, camera, transform, key_pts):\n \"\"\"Rotates a camera around its optical axis.\n\n Args:\n rotation: 4x4 rotation transform, c'_R_c\n image: Camera image, h x w x 4 (or 3).\n camera: 7-element camera parameters (fx, fy, cx, cy, baseline, resx, resy)\n transform: 4x4 transform matrix, w_T_c (camera-to-world).\n key_pts: Nx4 u,v,d,w image keypoints, in pixel coordinates.\n\n Returns:\n Rotated image, zero-filled\n Updated transform w_T_c' = w_T_c * P * c_R_c' * Q\n updated keypoints u,v,d,w, Nx4\n visibility vector for keypoint, N\n\n Keypoints are converted by P * c'_R_c * Q\n \"\"\"\n\n def in_bounds(pt, bounds):\n if (pt[0] >= 0 and pt[0] <= bounds[0] and pt[1] >= 0 and\n pt[1] <= bounds[1]):\n return 1.0\n else:\n return 0.0\n\n cam_pb = cam_array_to_pb(camera)\n pmat = p_matrix_from_camera(cam_pb)\n qmat = q_matrix_from_camera(cam_pb)\n tp = np.dot(transform, np.dot(pmat, np.dot(np.linalg.inv(rotation), qmat)))\n key_pts_p = project_np(\n np.dot(pmat, np.dot(rotation, qmat)), np.transpose(key_pts))\n kmat = k_matrix_from_camera(cam_pb)\n hmat = kmat.dot(rotation[:3, :3].transpose()).dot(np.linalg.inv(kmat))\n image_np = np.clip(image, 0.0, 0.9999)\n warped = warp(image_np, ProjectiveTransform(matrix=hmat))\n visible = np.array([\n in_bounds(key_pts_p[:2, i], camera[5:7]) for i in range(key_pts.shape[0])\n ])\n return warped, tp, key_pts_p.transpose(), visible\n\n\ndef warp_homography(res, scale, shear, flip):\n \"\"\"Returns a homography for image scaling, shear and flip.\n\n Args:\n res: resolution of the image, [x_res, y_res].\n scale: scale factor [x_scale, y_scale].\n shear: shear in [x_deg, y_deg].\n flip: boolean [x_flip, y_flip].\n \"\"\"\n center_mat = np.eye(3)\n center_mat[0, 2] = -res[0] / 2.0\n center_mat[1, 2] = -res[1] / 2.0\n cmat_inv = np.linalg.inv(center_mat)\n\n flip_mat = np.eye(3)\n if flip[0]:\n flip_mat[0, 0] = -1\n if flip[1]:\n flip_mat[1, 1] = -1\n\n shear_mat = np.eye(3)\n shear_mat[0, 1] = math.tan(math.radians(shear[0]))\n shear_mat[1, 0] = math.tan(math.radians(shear[1]))\n\n scale_mat = np.eye(3)\n scale_mat[0, 0] = scale[0]\n scale_mat[1, 1] = scale[1]\n\n return cmat_inv.dot(scale_mat.dot(shear_mat.dot(flip_mat.dot(center_mat))))\n\n\ndef do_rotation(image, image2, transform, camera, key_pts, visible, rotation):\n \"\"\"Add a random rotation about the camera centerpoint.\n\n Args:\n image: HxWx4 image, left image if stereo; can be uint8 or float.\n image2: HxWx4 image, right image if stereo, or None\n transform: 4x4 to_world transform.\n camera: 7-element camera parameters.\n key_pts: Nx4 uvdw keypoints.\n visible: Visibility prediate for keypoints.\n rotation: Rotation as 3-tuple, XYZ axes.\n\n Returns:\n image: Warped by random rotation, float32.\n transform: Updated to_world transform.\n key_pts: updated uvdw keypoints.\n visible: visibility vector for the keypoints.\n \"\"\"\n image = image_uint8_to_float(image)\n image2 = image_uint8_to_float(image2)\n area, _ = get_area(image)\n if area < 10: # Something is wrong here.\n return image, image2, transform, key_pts, visible\n\n rotation = (float(rotation[0]), float(rotation[1]), float(rotation[2]))\n while True:\n rot = rotation_transform(\n random.uniform(-rotation[0], rotation[0]),\n random.uniform(-rotation[1], rotation[1]),\n random.uniform(-rotation[2], rotation[2]))\n image_p, transform_p, key_pts_p, visible_p = rotate_camera(\n rot, image, camera, transform, key_pts)\n area_p, _ = get_area(image)\n if float(area_p) / area > 0.6:\n if image2 is not None:\n image2_p, _, _, _ = rotate_camera(rot, image2, camera, transform,\n key_pts)\n else:\n image2_p = image_p\n break\n\n # Warp function converts images to float64, this converts back.\n return (image_p.astype(np.float32), image2_p.astype(np.float32),\n transform_p.astype(np.float32), key_pts_p.astype(np.float32),\n visible_p.astype(np.float32))\n\n\ndef do_2d_homography(image, image2, scale, shear, flip, mirrored, split):\n \"\"\"Add random 2D transforms to input images.\n\n Images are warped according to the 2D transforms of scaling,\n shear and flip. The 2D homogenous transform inverse is returned,\n so that keypoints can be adjusted after they are predicted.\n Transforms that preserve horizontal epipolar lines are vertical flip,\n X-axis shear, mirroring, and scaling.\n TODO: visibility analysis.\n\n Args:\n image: HxWx4 image, left image if stereo; can be uint8 or float.\n image2: HxWx4 image, right image if stereo, or None\n scale: floating point bounds, uniform random scale, e.g., [0.8, 1.2].\n shear: x,y shear max bounds for uniform random shear, in degrees.\n flip: [True, True] if images are randomly flipped horizontal, vertical.\n mirrored: True if images are mirrored.\n split: train / eval split.\n\n Returns:\n image: Warped by random transform, float32.\n image2: Warped by same random transform, float32.\n homography: 3x3 homography matrix for the warp.\n \"\"\"\n if (not mirrored) and not (split == 'train' and (scale or shear or flip)):\n return image, image2, np.eye(3, dtype=np.float32)\n\n if not scale:\n scale = [1.0, 1.0]\n if not shear:\n shear = [0.0, 0.0]\n if not flip:\n flip = [False, False]\n image = image_uint8_to_float(image)\n image2 = image_uint8_to_float(image2)\n if mirrored:\n flip = [False, True]\n else:\n flip = [random.choice([False, flip[0]]), random.choice([False, flip[1]])]\n hom = warp_homography((image.shape[1], image.shape[0]), [\n 1.0, random.uniform(scale[0], scale[1])\n ], [random.uniform(-shear[0], shear[0]),\n random.uniform(-shear[1], shear[1])], flip)\n if np.allclose(hom, np.eye(3)):\n return image, image2, np.eye(3, dtype=np.float32)\n hom_inv = np.linalg.inv(hom)\n image_p = warp_2d(image, hom_inv)\n image2_p = warp_2d(image2, hom_inv)\n # Warp function converts images to float64, this converts back.\n return (image_p.astype(np.float32), image2_p.astype(np.float32),\n hom_inv.astype(np.float32))\n\n\ndef warp_2d(image, hom):\n image_np = np.clip(image, 0.0, 0.9999)\n warped = warp(image_np, ProjectiveTransform(matrix=hom))\n return warped\n\n\n# Returns a 2D gaussian centered on mean (pix coords, float) with\n# variance var (pixels, float).\ndef gauss2d(mean, var, size):\n x = np.arange(0, size[0])\n y = np.arange(0, size[1])\n x, y = np.meshgrid(x, y)\n mx, my = mean\n vx, vy = var\n return np.float32(1. / (2. * np.pi * vx * vy) *\n np.exp(-((x - mx)**2. / (2. * vx**2.) + (y - my)**2. /\n (2. * vy**2.))))\n\n\n# Normalize so the peak is 1.0.\ndef norm_gauss2d(mean, var, size):\n g2d = gauss2d(mean, var, size)\n m = np.max(g2d)\n if m <= 0.0:\n return g2d\n return g2d * (1.0 / np.max(g2d))\n\n\n# Make an inverse gaussian for exclusion of a prob field.\ndef inv_gauss(mean, var, size):\n g = gauss2d(mean, var, size)\n m = np.max(g)\n g_inv = (m - g) * (1.0 / m)\n return g_inv\n\n\ndef project_uvd(mat, uvd, offset):\n uvw = np.array([uvd[0] - offset[0], uvd[1] - offset[1], 1.0])\n uvwt = mat.dot(uvw)\n return uvwt[:2] / (uvwt[2] + 1e-10)\n\n\ndef do_vertical_flip(image, image2, mirrored):\n \"\"\"Flip image vertically.\n\n The 2D homogenous transform inverse is returned,\n so that keypoints can be adjusted after they are predicted.\n\n Args:\n image: HxWx4 image, left image if stereo; can be uint8 or float.\n image2: HxWx4 image, right image if stereo, or None.\n mirrored: True if image is mirrored.\n\n Returns:\n image: flipped vertically.\n image2: flipped vertically.\n homography: 3x3 homography matrix for vertical flip.\n \"\"\"\n if not mirrored:\n return image, image2, np.eye(3, dtype=np.float32)\n image = image_uint8_to_float(image)\n image2 = image_uint8_to_float(image2)\n image_p = np.flipud(image)\n image2_p = np.flipud(image2)\n hom = warp_homography(\n (image.shape[1], image.shape[0]),\n [1.0, 1.0], # Scale (none).\n [0.0, 0.0], # Shear (none).\n [False, True])\n return image_p, image2_p, np.linalg.inv(hom).astype(np.float32)\n\n\n# Returns gaussian 2Ds with shape [num_kpts, h, w].\n# keys_uvd has shape [num_kps, 4]\ndef do_spatial_prob(keys_uvd, hom, offset, var, size):\n hom_inv = np.linalg.inv(hom)\n uvs = [project_uvd(hom_inv, uvd, offset) for uvd in keys_uvd]\n probs = [inv_gauss(uv, [var, var], size) for uv in uvs]\n return np.array(probs, dtype=np.float32)\n\n\n# Largest fraction of object that can be occluded.\ndef do_occlude(image, image2, occ_fraction=0.0):\n \"\"\"Add an elliptical occlusion to the RGBA image.\n\n Args:\n image: RGBA images with A channel @ 255 for valid object.\n image2: RGBA images, right stereo.\n occ_fraction: fraction of image to be occluded.\n\n Returns:\n Modified image.\n Modifies image in place.\n \"\"\"\n area, inds = get_area(image)\n if area < 50:\n return image, image2\n radius = 2.0 * np.sqrt(area / np.pi) * occ_fraction\n\n for _ in range(0, 1):\n i = random.randint(0, area - 1)\n ind = (inds[0][i], inds[1][i])\n rr, cc = ellipse(\n ind[0],\n ind[1],\n random.uniform(1.0, radius),\n random.uniform(1.0, radius),\n shape=image.shape[0:2],\n rotation=random.uniform(-1.0, 1.0) * np.pi)\n image[rr, cc, 3] = 0\n image2[rr, cc, 3] = 0\n\n return image, image2\n\n\ndef do_motion_blur(image, distance, angle):\n \"\"\"Random fake motion blur by compositing in the x,y plane of the image.\n\n Args:\n image: tensor of images, floating point [0,1], 3 or 4 channels.\n distance: how far to move, in pixels <min, max>.\n angle: how much to rotate, in degrees <min, max>.\n\n Returns:\n Updated image with motion blur.\n \"\"\"\n if not distance[1]: # No blur.\n return image\n dist = random.uniform(*distance) * 0.5\n ang = math.radians(random.uniform(*angle))\n x, y = dist * math.cos(ang), dist * math.sin(ang)\n rows, cols = image.shape[:2]\n im = np.array([[1, 0, x], [0, 1, y]])\n im1 = cv2.warpAffine(image, im, (cols, rows))\n im = np.array([[1, 0, 2 * x], [0, 1, 2 * y]])\n im2 = cv2.warpAffine(image, im, (cols, rows))\n im = np.array([[1, 0, -x], [0, 1, -y]])\n im3 = cv2.warpAffine(image, im, (cols, rows))\n im = np.array([[1, 0, -2 * x], [0, 1, -2 * y]])\n im4 = cv2.warpAffine(image, im, (cols, rows))\n im = (image + im1 + im2 + im3 + im4) * 0.2\n np.clip(im, 0.0, 1.0, im)\n return im\n\n\ndef do_composite(image, bg_fname, sigma, motion, noise, gamma):\n \"\"\"Composite a background image onto the foreground.\n\n Args:\n image: original image, floating point [0,1].\n bg_fname: background image file name, None or empty string if none.\n sigma: blur in pixels; single value or range.\n motion: 4-tuple <min_pix_move, max_pix_move, min_deg_angle, max_deg angle>.\n noise: pixel noise in the range 0-255, either single value or range.\n gamma: gamma correction to be applied to image, 0 for none.\n\n Returns:\n Updated image.\n \"\"\"\n\n def make_random(x):\n # Arg x can be list, tuple, numpy.ndarray\n if isinstance(x, list) or isinstance(x, tuple):\n x = np.array(x)\n assert isinstance(\n x, np.ndarray), 'Argument to do_composite must be list or array'\n if x.size == 0:\n return None\n elif x.size == 1:\n return x[0]\n else:\n return random.uniform(x[0], x[1])\n\n if motion[1]:\n image = do_motion_blur(image, motion[:2], motion[2:])\n\n ys, xs, _ = image.shape\n if bg_fname:\n scene = read_image(bg_fname) * (1.0 / 255.0)\n if random.choice([True, False]):\n scene = np.flipud(scene)\n if random.choice([True, False]):\n scene = np.fliplr(scene)\n yss, xss = scene.shape[0], scene.shape[1]\n assert yss > ys, 'Background image must be larger than training image'\n assert xss > xs, 'Background image must be larger than training image'\n\n # Adjust gamma of image.\n gamma = make_random(gamma)\n if gamma is not None:\n image[:, :, :3] = adjust_gamma(image[:, :, :3], gamma)\n # Add noise to object.\n noise = make_random(noise)\n if noise is not None:\n image[:, :, :3] += np.random.randn(ys, xs, 3) * noise * 0.5 / 255.\n np.clip(image, 0.0, 1.0, image)\n\n # Cut out ellipse where image alpha is 0.\n if bg_fname:\n ul_y = random.randint(0, yss - ys - 1)\n ul_x = random.randint(0, xss - xs - 1)\n scene_crop = scene[ul_y:ul_y + ys, ul_x:ul_x + xs, :]\n mask = image[:, :, 3]\n rgbmask = np.stack([mask, mask, mask], axis=2)\n image[:, :, :3] = scene_crop * (1.0 - rgbmask) + image[:, :, :3] * rgbmask\n else:\n image[image[:, :, 3] == 0, 0:3] = 0.5\n\n # Add gaussian blur and noise.\n sigma = make_random(sigma)\n im = np.copy(image[:, :, :3]) # Need copy to preserve float32\n gaussian(image[:, :, :3], sigma, multichannel=True, output=im)\n # Add noise to whole scene, after blur.\n if noise is not None:\n im[:, :, :3] += np.random.randn(ys, xs, 3) * noise * 0.5 / 255.\n np.clip(im, 0.0, 1.0, im)\n\n return im\n\n\n# Returns area in pixels.\n# Works for both uint8 and float32 images.\ndef get_area(image):\n inds = np.nonzero(image[:, :, 3] > 0)\n area = inds[0].shape[0]\n return area, inds\n\n\ndef do_occlude_crop(image,\n image2,\n key_pts,\n key_pts_r,\n crop,\n visible,\n dither,\n var_offset=False):\n \"\"\"Crop area around the object.\n\n Crop is [W, H, R]', where 'R' is right-disparity offset; or else [].\n Images can be either floating-point or uint8.\n\n Args:\n image: left image.\n image2: right image.\n key_pts: left keypoints.\n key_pts_r: right keypoints.\n crop: crop is [W, H, R]', where 'R' is right-disparity offset; or else [].\n visible: visibility status of keypoints, modified by function.\n dither: amount to dither the crop.\n var_offset: vary the offset between left and right images.\n\n Returns:\n image: cropped left image.\n image2: cropped right image.\n offset: offset of the crop in the original image.\n visible: visibility status of the keypoints.\n \"\"\"\n\n offset = np.array([0, 0, 0], dtype=np.float32)\n crop = np.array(crop)\n if crop.size == 0:\n return image, image2, offset, visible\n nxs, nys = crop[0], crop[1]\n\n def do_crop(im, left_x, top_y, margin=10.0):\n y, x, _ = im.shape\n x -= margin\n y -= margin\n right_x = left_x + nxs\n bot_y = top_y + nys\n if (left_x < margin or left_x > x or right_x < margin or right_x > x or\n top_y < margin or top_y > y or bot_y < margin or bot_y > y):\n visible[:] = 0.0\n return im[0:nys, 0:nxs, :]\n return im[top_y:bot_y, left_x:right_x, :]\n\n centroid = np.mean(key_pts, axis=0)[0:2]\n centroid += np.random.uniform(low=-dither, high=dither, size=(2))\n off_x = int(centroid[0] - nxs / 2 - (nxs - nys) / 2)\n off_y = int(centroid[1] - nys / 2)\n image = do_crop(image, off_x, off_y)\n off_d = crop[2]\n if var_offset:\n off_d = int(centroid[0] - np.mean(key_pts_r, axis=0)[0])\n image2 = do_crop(image2, off_x - off_d, off_y)\n offset = np.array([off_x, off_y, off_d], dtype=np.float32)\n return image, image2, offset, visible\n\n\n# Meshing functions.\ndef farthest_point_sampling(point_set, k):\n \"\"\"Find the k most spread-out poses of a set of poses; translation only.\"\"\"\n num_pts = point_set.shape[0]\n start_idx = np.random.randint(num_pts)\n existing_set = np.expand_dims(point_set[start_idx], axis=0)\n rest_set = np.copy(point_set)\n np.delete(rest_set, start_idx, 0)\n\n existing_indices = [start_idx]\n rest_indices = np.arange(num_pts)\n np.delete(rest_indices, start_idx)\n\n for _ in range(k - 1):\n dist = (\n np.sum(np.square(existing_set), axis=1, keepdims=True) +\n np.sum(np.square(rest_set.T), axis=0, keepdims=True) -\n np.dot(existing_set, rest_set.T) * 2)\n min_dist = dist.min(axis=0)\n max_idx = min_dist.argmax()\n existing_set = np.concatenate(\n [existing_set, np.expand_dims(rest_set[max_idx], axis=0)], axis=0)\n existing_indices.append(rest_indices[max_idx])\n np.delete(rest_set, max_idx, 0)\n np.delete(rest_indices, max_idx)\n\n return existing_set, existing_indices\n\n\n# Class for holding a CAD object and its keypoints.\nclass MeshObj:\n \"\"\"Class for holding a CAD object and its keypoints.\"\"\"\n\n def __init__(self):\n self.keypoints = np.array([])\n self.vertices = np.array([])\n self.large_points = True\n\n def read_obj(self, path, num=300):\n \"\"\"Read in a .obj file, parse into vertices and keypoints.\"\"\"\n # Vertices are in label \"o mesh\".\n # Keypoints are in label \"o kp.NNN\".\n # Just read vertices, not other elements of the .obj file.\n kps = {}\n with open(path, 'r') as f:\n line = f.readline()\n while True:\n if not line:\n break\n if len(line) > 2 and line[:2] == 'o ':\n # New mesh.\n name = line[2:-1]\n vertices, line = self._read_sub_obj(f)\n if 'mesh' in name:\n self.vertices = vertices\n if 'kp' in name: # Keypoint object.\n kp_num = int(name.split('.')[1])\n kp_val = np.mean(vertices, axis=0)\n kps[kp_num] = kp_val\n else:\n line = f.readline()\n keypoints = [kps[i] for i in range(len(kps))]\n if not keypoints:\n print('Did not find any keypoints')\n return\n self.keypoints = np.array(keypoints)\n self.keypoints = np.concatenate(\n [self.keypoints, np.ones((self.keypoints.shape[0], 1))], axis=-1)\n self.xyzw = np.concatenate(\n [self.vertices, np.ones((self.vertices.shape[0], 1))], axis=-1)\n self.make_reduced(num)\n\n def make_reduced(self, num):\n self._make_colored_subset(num)\n self.xyzw_reduced = np.concatenate(\n [self.vertices_reduced,\n np.ones((self.vertices_reduced.shape[0], 1))],\n axis=-1)\n\n def _read_sub_obj(self, f):\n \"\"\"Read in all the vertices.\"\"\"\n # First read to the beginning of vertices.\n line = ''\n vertices = []\n while True:\n line = f.readline()\n if not line:\n return None\n if 'v ' in line:\n break\n\n # Now process all vertices.\n while True:\n elems = line[:-1].split(' ')\n if elems[0] != 'v':\n break\n vertices.append(np.array([float(x) for x in elems[1:]]))\n line = f.readline()\n if not line:\n break\n return np.array(vertices), line\n\n # Pick a subset of colored points for display.\n def _make_colored_subset(self, num):\n self.vertices_reduced, _ = farthest_point_sampling(self.vertices, num)\n colors = plt.cm.get_cmap('spring')\n zs = self.vertices_reduced[:, 2]\n self.reduced_colors = (255 *\n colors(np.interp(zs, (zs.min(), zs.max()),\n (0, 1)))[:, :3]).astype(np.uint8)\n\n def project_to_uvd(self, xyzs, p_matrix):\n \"\"\"Does a transform from CAD coords to kps coords, then projects to uvd.\"\"\"\n kps_t_mesh = ortho_procrustes(self.keypoints, xyzs.T[:, :3])\n uvd_t_mesh = p_matrix.dot(kps_t_mesh)\n self.uvds = project_np(uvd_t_mesh, self.xyzw.T).T\n self.uvds_reduced = project_np(uvd_t_mesh, self.xyzw_reduced.T).T\n\n def draw_points(self, image, offsets=(0, 0)):\n \"\"\"Draws u,v points on an image as circles.\"\"\"\n for i, pt in enumerate(self.uvds_reduced):\n u = int(pt[0] - offsets[0])\n v = int(pt[1] - offsets[1])\n if u < 0 or u >= image.shape[1] or v < 0 or v >= image.shape[0]:\n continue\n image[v, u, :] = self.reduced_colors[i, :]\n if self.large_points:\n if u > 0 and v > 0 and u < image.shape[1] - 1 and v < image.shape[0] - 1:\n for ui in range(-1, 2):\n for vi in range(-1, 2):\n image[v + vi, u + ui, :] = self.reduced_colors[i, :]\n return image\n\n def segmentation(self, size):\n \"\"\"Create segmentation image using morphology operations.\"\"\"\n mask = np.zeros(size)\n for pt in self.uvds:\n u = int(pt[0])\n v = int(pt[1])\n if u < 0 or u >= size[1] or v < 0 or v >= size[0]:\n continue\n mask[v, u] = 255\n kernel = np.ones((3, 3), np.uint8)\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # Converts to float.\n mask_dilated = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)\n border = mask_dilated - mask\n return mask.astype(np.uint8), border.astype(np.uint8)\n\n\n# Orthogonal procrustes method for two sets of 3D points.\n# Also does the initial translation to centroid.\n# Should work in degenerate cases: 1 or 2 points.\ndef ortho_procrustes(p_c, p_s):\n \"\"\"Return R,t of the best estimate transform on point clouds p_c and p_s.\"\"\"\n # No scaling. Transform is from p_c to p_s, i.e., T * p_c ~= p_s.\n # Format of args is numpy array, nx3 or nx4,d, each row a 3D point\n\n p_c = p_c[:, :3]\n p_s = p_s[:, :3]\n cm = np.mean(p_c, 0)\n pcn = p_c - cm # get mean of each dimension, subtract\n sm = np.mean(p_s, 0)\n psn = p_s - sm\n a_mat = psn.transpose().dot(pcn)\n u, _, vt = np.linalg.svd(a_mat)\n dd = np.eye(3)\n dd[2, 2] = np.linalg.det(u.dot(vt))\n rot = u.dot(dd.dot(vt)) # Should check for orthogonality.\n t = sm - rot.dot(cm)\n tfm = np.eye(4)\n tfm[0:3, 0:3] = rot\n tfm[0:3, 3] = t\n return tfm\n\n\n# Read in CAD model from a .obj file.\n# <path> is a file path from the data_tools/objects/ directory.\n# <num> is the number of points to use in the reduced set.\ndef read_mesh(path, num=300):\n obj = MeshObj()\n print('Reading obj file %s' % path)\n obj.read_obj(path, num)\n print('Obj file has %d vertices and %d keypoints' %\n (len(obj.vertices), len(obj.keypoints)))\n return obj\n\n\n# Error functions.\ndef project(tmat, tvec, tvec_transpose=False):\n \"\"\"Projects homogeneous 3D XYZ coordinates to image uvd coordinates.\"\"\"\n # <tvec> has shape [[N,] batch_size, 4, num_kp] or [batch_size, num_kp, 4].\n # <tmat> has shape [[N,] batch_size, 4, 4]\n # Return has shape [[N,] batch_size, 4, num_kp]\n\n tp = tf.matmul(tmat, tvec, transpose_b=tvec_transpose)\n # Using <3:4> instead of <3> preserves shape.\n tp = tp / (tp[Ellipsis, 3:4, :] + 1.0e-10)\n return tp\n\n\ndef world_error(labels, xyzw):\n xyzw = tf.transpose(xyzw, [0, 2, 1]) # [batch, 4, num_kp]\n # [batch, 4, num_kp]\n gt_world_coords = project(labels['to_world_L'], labels['keys_uvd_L'], True)\n sub = xyzw[:, :3, :] - gt_world_coords[:, :3, :]\n wd = tf.square(sub)\n wd = tf.reduce_sum(wd, axis=[-2]) # [batch, num_kp] result.\n wd = tf.sqrt(wd)\n return wd # [batch, num_kp]\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Input pipeline for Robust-fill dataset.\"\"\"\n\nimport tensorflow.compat.v2 as tf\n\nfrom latent_programmer.tasks.robust_fill import dsl\n\ngfile = tf.io.gfile\n\n\ndef create_dataset_from_tf_record(file_pattern, token_id_table, char_id_table):\n \"\"\"Returns an instance of tf.data.Dataset.\"\"\"\n\n filenames = gfile.glob(file_pattern)\n raw_dataset = tf.data.TFRecordDataset(filenames)\n\n char_table = tf.lookup.StaticVocabularyTable(\n tf.lookup.KeyValueTensorInitializer(\n # Add padding.\n [''] + list(char_id_table.keys()),\n [0] + list(char_id_table.values()),\n key_dtype=tf.string,\n value_dtype=tf.int64),\n len(char_id_table) + 1)\n\n def _parse_fn(record):\n \"\"\"Parses a record into a feature_dict.\"\"\"\n feature_values = tf.io.parse_single_example(\n serialized=record,\n features={\n 'i/o':\n tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'program_encoding':\n tf.io.FixedLenFeature([], tf.string, default_value=''),\n })\n\n ios = tf.strings.split(\n tf.strings.split(feature_values['i/o'], sep='>'), sep='<')\n ios = tf.strings.unicode_split(ios, 'UTF-8')\n ios = ios.to_tensor()\n ios = char_table.lookup(ios) # Map characters to integer tokens.\n\n program_encoding = tf.strings.to_number(\n tf.strings.split(feature_values['program_encoding'], sep=' '),\n out_type=tf.int32)\n # Add EOS token.\n eos_token = token_id_table[dsl.EOS]\n program_encoding = tf.concat([program_encoding, [eos_token]], axis=-1)\n return ios[:, 0], ios[:, 1], program_encoding\n\n dataset = raw_dataset.map(_parse_fn)\n return dataset\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Script to colorize or recolorize a directory of images.\n\nInstructions\n------------\n1. Download pretrained models from\nhttps://storage.cloud.google.com/gresearch/coltran/coltran.zip\n\n2. Set the following variables:\n\n* LOGDIR - Checkpoint Directory to the corresponding checkpoints.\n* IMG_DIR - Directory with ground-truth grayscale or colored images.\n* STORE_DIR - Directory to store generated images.\n* MODE - \"colorize\" if IMG_DIR consists of grayscale images\n \"recolorize\" if IMG_DIR consists of colored images.\n\n2. Run the colorizer to get a coarsely colorized image. Set as follows:\n\npython -m coltran.custom_colorize --config=configs/colorizer.py \\\n--logdir=$LOGDIR/colorizer --img_dir=$IMG_DIR --store_dir=$STORE_DIR \\\n--mode=$MODE\n\nThe generated images will be stored in $STORE_DIR/stage1\n\n3. Run the color upsampler to upsample the coarsely colored image.\n\npython -m coltran.custom_colorize --config=configs/color_upsampler.py \\\n--logdir=$LOGDIR/color_upsampler --img_dir=$IMG_DIR --store_dir=$STORE_DIR \\\n--gen_data_dir=$STORE_DIR/stage1 --mode=$MODE\n\nThe generated images will be stored in $STORE_DIR/stage2\n\n4. Run the spatial upsampler to super-resolve into the final output.\n\npython -m coltran.custom_colorize --config=configs/spatial_upsampler.py \\\n--logdir=$LOGDIR/spatial_upsampler --img_dir=$IMG_DIR --store_dir=$STORE_DIR \\\n--gen_data_dir=$STORE_DIR/stage2 --mode=$MODE\n\nNotes\n-----\n* The model is pre-trained on ImageNet. Colorized images may reflect the biases\npresent in the ImageNet dataset.\n* Once in a while, there can be artifacts or anomalous colorizations\ndue to accumulation of errors.\nSee Section M of https://openreview.net/pdf?id=5NA1PinlGFu\n* Legacy images may have a different distribution as compared to the\ngrayscale images used to train the model. This might reflect in difference in\ncolorization fidelity between colorizing legacy images and our reported results.\n* Setting \"mode\" correctly is important.\nIf img_dir consists of grayscale images, it should be set to \"colorize\"\nif img_dir consists of colored images , it should be set to \"recolorize\".\n\n\"\"\"\nimport os\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport matplotlib.pyplot as plt\nfrom ml_collections import config_flags\nimport numpy as np\n\nimport tensorflow.compat.v2 as tf\n\nfrom coltran import datasets\nfrom coltran.models import colorizer\nfrom coltran.models import upsampler\nfrom coltran.utils import base_utils\nfrom coltran.utils import datasets_utils\nfrom coltran.utils import train_utils\n\n\nflags.DEFINE_string('img_dir', None,\n 'Path for images needed to be colorized / recolorized.')\nflags.DEFINE_string('logdir', '/tmp/svt', 'Checkpoint directory.')\nflags.DEFINE_string('gen_data_dir', None,\n 'Path to images generated from the previous stages. '\n 'Has to be set if the model is the color or spatial '\n 'upsampler.')\nflags.DEFINE_string('store_dir', None, 'Path to store generated images.')\nflags.DEFINE_string('master', 'local',\n 'BNS name of the TensorFlow master to use.')\nflags.DEFINE_string('tpu_worker_name', 'tpu_worker', 'Name of the TPU worker.')\nflags.DEFINE_enum('accelerator_type', 'GPU', ['CPU', 'GPU', 'TPU'],\n 'Hardware type.')\nflags.DEFINE_enum('mode', 'colorize', ['colorize', 'recolorize'],\n 'Whether to colorizer or recolorize images.')\nflags.DEFINE_integer('steps_per_summaries', 100, 'Steps per summaries.')\nflags.DEFINE_integer('batch_size', None,\n 'Batch size. If not provided, use the optimal batch-size '\n 'for each model.')\nconfig_flags.DEFINE_config_file(\n 'config',\n default='test_configs/colorizer.py',\n help_string='Training configuration file.')\nFLAGS = flags.FLAGS\n\n\ndef create_grayscale_dataset_from_images(image_dir, batch_size):\n \"\"\"Creates a dataset of grayscale images from the input image directory.\"\"\"\n def load_and_preprocess_image(path, child_path):\n image_str = tf.io.read_file(path)\n num_channels = 1 if FLAGS.mode == 'colorize' else 3\n image = tf.image.decode_image(image_str, channels=num_channels)\n\n # Central crop to square and resize to 256x256.\n image = datasets.resize_to_square(image, resolution=256, train=False)\n\n # Resize to a low resolution image.\n image_64 = datasets_utils.change_resolution(image, res=64)\n if FLAGS.mode == 'recolorize':\n image = tf.image.rgb_to_grayscale(image)\n image_64 = tf.image.rgb_to_grayscale(image_64)\n return image, image_64, child_path\n\n child_files = tf.io.gfile.listdir(image_dir)\n files = [os.path.join(image_dir, file) for file in child_files]\n files = tf.convert_to_tensor(files, dtype=tf.string)\n dataset = tf.data.Dataset.from_tensor_slices((files, child_files))\n dataset = dataset.map(load_and_preprocess_image)\n return dataset.batch(batch_size=batch_size)\n\n\ndef build_model(config):\n \"\"\"Builds model.\"\"\"\n name = config.model.name\n optimizer = train_utils.build_optimizer(config)\n\n zero_64 = tf.zeros((1, 64, 64, 3), dtype=tf.int32)\n zero_64_slice = tf.zeros((1, 64, 64, 1), dtype=tf.int32)\n zero = tf.zeros((1, 256, 256, 3), dtype=tf.int32)\n zero_slice = tf.zeros((1, 256, 256, 1), dtype=tf.int32)\n\n if name == 'coltran_core':\n model = colorizer.ColTranCore(config.model)\n model(zero_64, training=False)\n elif name == 'color_upsampler':\n model = upsampler.ColorUpsampler(config.model)\n model(inputs=zero_64, inputs_slice=zero_64_slice, training=False)\n elif name == 'spatial_upsampler':\n model = upsampler.SpatialUpsampler(config.model)\n model(inputs=zero, inputs_slice=zero_slice, training=False)\n\n ema_vars = model.trainable_variables\n ema = train_utils.build_ema(config, ema_vars)\n return model, optimizer, ema\n\n\ndef get_batch_size(name):\n \"\"\"Gets optimal batch-size based on model.\"\"\"\n if FLAGS.batch_size is not None:\n return FLAGS.batch_size\n elif 'upsampler' in name:\n return 5\n return 20\n\n\ndef get_store_dir(name, store_dir):\n store_dict = {\n 'coltran_core': 'stage1',\n 'color_upsampler': 'stage2',\n 'spatial_upsampler': 'final'}\n store_dir = os.path.join(store_dir, store_dict[name])\n tf.io.gfile.makedirs(store_dir)\n return store_dir\n\n\ndef main(_):\n config, store_dir, img_dir = FLAGS.config, FLAGS.store_dir, FLAGS.img_dir\n assert store_dir is not None\n assert img_dir is not None\n model_name, gen_data_dir = config.model.name, FLAGS.gen_data_dir\n needs_gen = model_name in ['color_upsampler', 'spatial_upsampler']\n\n batch_size = get_batch_size(model_name)\n store_dir = get_store_dir(model_name, store_dir)\n num_files = len(tf.io.gfile.listdir(img_dir))\n\n if needs_gen:\n assert gen_data_dir is not None\n gen_dataset = datasets.create_gen_dataset_from_images(gen_data_dir)\n gen_dataset = gen_dataset.batch(batch_size)\n gen_dataset_iter = iter(gen_dataset)\n\n dataset = create_grayscale_dataset_from_images(FLAGS.img_dir, batch_size)\n dataset_iter = iter(dataset)\n\n model, optimizer, ema = build_model(config)\n checkpoints = train_utils.create_checkpoint(model, optimizer=optimizer,\n ema=ema)\n train_utils.restore(model, checkpoints, FLAGS.logdir, ema)\n num_steps_v = optimizer.iterations.numpy()\n logging.info('Producing sample after %d training steps.', num_steps_v)\n\n num_epochs = int(np.ceil(num_files / batch_size))\n logging.info(num_epochs)\n\n for _ in range(num_epochs):\n gray, gray_64, child_paths = next(dataset_iter)\n\n if needs_gen:\n prev_gen = next(gen_dataset_iter)\n\n if model_name == 'coltran_core':\n out = model.sample(gray_64, mode='sample')\n samples = out['auto_sample']\n elif model_name == 'color_upsampler':\n prev_gen = base_utils.convert_bits(prev_gen, n_bits_in=8, n_bits_out=3)\n out = model.sample(bit_cond=prev_gen, gray_cond=gray_64)\n samples = out['bit_up_argmax']\n else:\n prev_gen = datasets_utils.change_resolution(prev_gen, 256)\n out = model.sample(gray_cond=gray, inputs=prev_gen, mode='argmax')\n samples = out['high_res_argmax']\n\n child_paths = child_paths.numpy()\n child_paths = [child_path.decode('utf-8') for child_path in child_paths]\n logging.info(child_paths)\n\n for sample, child_path in zip(samples, child_paths):\n write_path = os.path.join(store_dir, child_path)\n logging.info(write_path)\n sample = sample.numpy().astype(np.uint8)\n logging.info(sample.shape)\n with tf.io.gfile.GFile(write_path, 'wb') as f:\n plt.imsave(f, sample)\n\n\nif __name__ == '__main__':\n app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for bi-tempered loss.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nfrom absl.testing import absltest\nimport tensorflow as tf\n\nfrom bitempered_loss import loss\n\npython_version = \"PY3\"\n\n\nclass LossTest(tf.test.TestCase):\n\n def test_normalization(self):\n \"\"\"Test the normalization constant.\"\"\"\n activations = tf.random.normal(shape=[100, 50000])\n for t in [0.99, 1.01]:\n normalization_constants = loss.compute_normalization(\n activations, t, num_iters=20)\n self.assertEqual(normalization_constants.shape, [100, 1])\n probabilities = tf.reduce_sum(\n loss.exp_t(activations - normalization_constants, t), -1)\n self.assertAllClose(probabilities.numpy(), [1.0] * 100, atol=1e-5)\n for t in [0.1, 2.0]:\n normalization_constants = loss.compute_normalization(\n activations, t, num_iters=20)\n probabilities = tf.reduce_sum(\n loss.exp_t(activations - normalization_constants, t), -1)\n self.assertAllClose(probabilities.numpy(), [1.0] * 100, atol=1e-5)\n\n def test_limit_case_logistic_loss(self):\n \"\"\"Test for checking if t1 = t2 = 1.0 yields the logistic loss.\"\"\"\n labels = tf.constant([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])\n activations = tf.random.normal(shape=[3, 3])\n actual_loss = loss.bi_tempered_logistic_loss(activations, labels, 1.0,\n 1.0)\n logistic_loss = tf.nn.softmax_cross_entropy_with_logits(\n logits=activations, labels=labels)\n actual_loss_out, logistic_loss_out = (\n actual_loss.numpy(), logistic_loss.numpy())\n self.assertAllClose(actual_loss_out, logistic_loss_out)\n\n def test_loss_value(self):\n \"\"\"Test the loss based on precomputed values.\"\"\"\n labels = tf.constant([[0.2, 0.3, 0.5], [0.6, 0.3, 0.1], [0.2, 0.8, 0.0]])\n activations = [[-0.5, 0.1, 2.0], [0.1, 1.5, -5.0], [4.0, -3.0, -6.0]]\n actual_loss = loss.bi_tempered_logistic_loss(activations, labels, 0.5,\n 1.5)\n self.assertAllClose(actual_loss.numpy(),\n [0.02301914, 0.18972909, 0.93874922])\n actual_loss = loss.bi_tempered_logistic_loss(activations, labels, 0.5,\n 0.8, num_iters=20)\n self.assertAllClose(actual_loss.numpy(),\n [0.21646356, 0.41836615, 1.33997854])\n\n def test_constant_shift(self):\n \"\"\"Test if adding a constant to all activations is vacuous.\"\"\"\n labels = tf.constant([[0.2, 0.3, 0.5], [0.4, 0.4, 0.2], [0.7, 0.2, 0.1]])\n activations = tf.random.normal(shape=[3, 3])\n bias = tf.random.normal(shape=[3, 1])\n for t2 in [0.8, 1.2]:\n actual_loss = loss.bi_tempered_logistic_loss(\n activations, labels, 0.5, t2)\n shifted_loss = loss.bi_tempered_logistic_loss(\n activations + bias, labels, 0.5, t2)\n actual_loss_out, shifted_loss_out = (\n actual_loss.numpy(), shifted_loss.numpy())\n self.assertAllClose(actual_loss_out, shifted_loss_out)\n\n def test_gradient_error(self):\n \"\"\"Compare custom gradient with tf.GradientTape.\"\"\"\n labels = tf.constant([[0.4, 0.3, 0.3], [0.8, 0.1, 0.1], [0.0, 0.0, 1.0],\n [0.0, 1.0, 0.0]])\n activations = tf.random.normal(shape=[4, 3])\n for t1, t2 in [[0.5, 1.0], [1.0, 1.5], [0.5, 1.5]]:\n with tf.GradientTape(persistent=True) as tape:\n tape.watch(activations)\n internal_loss = loss._internal_bi_tempered_logistic_loss(\n activations, labels, t1, t2)\n actual_loss = loss.bi_tempered_logistic_loss(\n activations, labels, t1, t2)\n numerical_gradient = tape.gradient(internal_loss, activations)\n actual_gradient = tape.gradient(actual_loss, activations)\n internal_loss_out, actual_loss_out = (\n internal_loss.numpy(), actual_loss.numpy())\n numerical_gradient_out, actual_gradient_out = (\n numerical_gradient.numpy(), actual_gradient.numpy())\n self.assertEqual(actual_gradient_out.shape, (4, 3))\n self.assertAllClose(actual_loss_out, internal_loss_out, atol=1e-5)\n self.assertAllClose(\n actual_gradient_out, numerical_gradient_out, atol=1e-4)\n\n def test_label_smoothing(self):\n \"\"\"Test label smoothing.\"\"\"\n labels = tf.constant([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])\n activations = [[-0.5, 0.1, 2.0], [0.1, 1.5, -5.0], [4.0, -3.0, -6.0]]\n actual_loss = loss.bi_tempered_logistic_loss(\n activations, labels, 0.5, 1.5, label_smoothing=0.1)\n actual_loss_out = actual_loss.numpy()\n self.assertAllClose(\n actual_loss_out, [0.76652711, 0.08627685, 1.35443510], atol=1e-5)\n\n def test_binary_logistic_loss(self):\n \"\"\"Test binary logistic loss.\"\"\"\n labels = tf.constant([1.0, 0.0])\n activations = [0.0, 0.0]\n actual_loss = loss.bi_tempered_binary_logistic_loss(activations, labels,\n 1.0, 1.0)\n actual_loss_out = actual_loss.numpy()\n self.assertAllClose(actual_loss_out, [0.69314718, 0.69314718], atol=1e-5)\n\n def test_dynamic_temperatures(self):\n \"\"\"Test changing temperatures dynamically.\"\"\"\n labels = tf.constant([[0.2, 0.5, 0.3]])\n activations = [[-0.5, 0.1, 2.0]]\n actual_loss = functools.partial(\n loss.bi_tempered_logistic_loss,\n activations=activations,\n labels=labels,\n num_iters=5)\n t1_values = [1.0, 0.9, 0.8, 0.7]\n t2_values = [1.0, 1.1, 1.2, 1.3]\n loss_values = [[1.6583576], [0.45677936], [0.34298314], [0.26295574]]\n loss_out = []\n for t1_value, t2_value in zip(t1_values, t2_values):\n loss_out.append(actual_loss(t1=t1_value, t2=t2_value).numpy())\n self.assertAllClose(loss_values, loss_out, atol=1e-5)\n\n def test_sparse_loss(self):\n \"\"\"Test int labels.\"\"\"\n labels = tf.constant([0, 2, 1, 0])\n activations = [[-0.5, 0.1, 2.0], [0.1, 1.5, -5.0], [4.0, -3.0, -6.0],\n [-1.5, 0.7, 5.2]]\n actual_loss = loss.bi_tempered_logistic_loss(activations,\n tf.one_hot(labels, 3), 0.5,\n 1.5)\n sparse_loss = loss.sparse_bi_tempered_logistic_loss(activations, labels,\n 0.5, 1.5)\n actual_loss_out = actual_loss.numpy()\n sparse_loss_out = sparse_loss.numpy()\n self.assertAllClose(actual_loss_out, sparse_loss_out)\n labels = tf.constant([[0, 2], [1, 0]])\n activations = [[[-0.5, 0.1, 2.0], [0.1, 1.5, -5.0]],\n [[4.0, -3.0, -6.0], [-1.5, 0.7, 5.2]]]\n actual_loss = loss.bi_tempered_logistic_loss(activations,\n tf.one_hot(labels, 3), 0.5,\n 1.5)\n sparse_loss = loss.sparse_bi_tempered_logistic_loss(activations, labels,\n 0.5, 1.5)\n actual_loss_out = actual_loss.numpy()\n sparse_loss_out = sparse_loss.numpy()\n self.assertAllClose(actual_loss_out, sparse_loss_out)\n\n def test_tempered_softmax(self):\n # Test softmax function with different temperatures.\n activations = [[-0.5, 0.1, 2.0], [0.1, 1.5, -5.0], [4.0, -3.0, -6.0]]\n # Test with temperature = 1.0, which should recover regular\n # softmax probabilities.\n softmax_probabilities_t_1 = loss.tempered_softmax(\n activations, t=1.0).numpy()\n vanilla_softmax_probabilties = tf.nn.softmax(activations).numpy()\n self.assertAllClose(vanilla_softmax_probabilties,\n softmax_probabilities_t_1)\n softmax_probabilities_t_4 = loss.tempered_softmax(\n activations, t=4.0).numpy()\n expected_softmax_probabilities_t_4 = ([[\n 0.3205458, 0.32714278, 0.3523402\n ], [0.3430056, 0.36491093,\n 0.29220778], [0.41369352, 0.30534995, 0.28299212]])\n self.assertAllClose(expected_softmax_probabilities_t_4,\n softmax_probabilities_t_4)\n\n def test_tempered_sigmoid(self):\n # Test sigmoid function with different temperatures.\n activations = [0.0, 3.0, 6.0]\n # Test with temperature = 1.0, which should recover regular\n # sigmoid probabilities.\n sigmoid_probabilities_t_1 = loss.tempered_sigmoid(\n activations, t=1.0).numpy()\n vanilla_softmax_probabilties = tf.nn.sigmoid(activations).numpy()\n self.assertAllClose(vanilla_softmax_probabilties,\n sigmoid_probabilities_t_1)\n sigmoid_probabilities_t_4 = loss.tempered_sigmoid(\n activations, t=4.0).numpy()\n expected_sigmoid_probabilities_t_4 = [0.5, 0.58516014, 0.6421035]\n self.assertAllClose(expected_sigmoid_probabilities_t_4,\n sigmoid_probabilities_t_4)\n\n\nif __name__ == \"__main__\":\n absltest.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Relights a given scene from stack_folder under sample illuminations.\"\"\"\n\nimport tensorflow.compat.v1 as tf\n\nfrom factorize_a_city.libs import image_alignment\nfrom factorize_a_city.libs import network\nfrom factorize_a_city.libs import stack_io\n\ntf.flags.DEFINE_string(\n \"stack_folder\", \"\", \"Folder containing input panoramas of the same scene. \"\n \"Relights the input scene with sample illuminations.\")\ntf.flags.DEFINE_string(\"output_dir\", \"relit_results\",\n \"Where to save the results.\")\nFLAGS = tf.flags.FLAGS\n\n\ndef main(unused_argv):\n if not FLAGS.stack_folder:\n raise ValueError(\"stack_folder was not defined\")\n\n # Load example stacks. Each panorama has shape [384, 960, 3] and has values\n # between [0, 1].\n (permanent_stack, alignment_params) = stack_io.read_stack(FLAGS.stack_folder)\n\n # Load example azimuth and illumination samples.\n azimuth, lighting_context = stack_io.load_sample_illuminations()\n\n permanent_stack = tf.constant(permanent_stack, dtype=tf.float32)\n azimuth_factors = tf.constant(azimuth, dtype=tf.float32)\n lighting_context_factors = tf.constant(lighting_context, dtype=tf.float32)\n\n # Align images using learnt parameters.\n alignment_module = image_alignment.ImageAlignment(regularization=0.3)\n aligned_stack = alignment_module.align_images(permanent_stack,\n alignment_params)\n\n factorize_model = network.FactorizeEncoderDecoder(\n {\n \"lighting_dim\": 32,\n \"permanent_dim\": 16\n }, is_training=False)\n stack_factors = factorize_model.compute_decomposition(aligned_stack)\n permanent_factor = stack_factors[\"permanent_factor\"]\n permanent_factor = tf.tile(permanent_factor[:1], [azimuth.shape[0], 1, 1, 1])\n shading_image = factorize_model.generate_shading_image(\n permanent_factor, lighting_context_factors, azimuth_factors)\n relit_results = network.recomposite_from_log_components(\n stack_factors[\"log_reflectance\"], shading_image)\n # Restore factorization network weights from ckpt.\n tf.train.init_from_checkpoint(\"./factorize_a_city/ckpt/factorize_model.ckpt\",\n {\"decomp_internal/\": \"decomp_internal/\"})\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n out = sess.run(relit_results)\n stack_io.write_stack_images(FLAGS.output_dir, out / 255.)\n\n\nif __name__ == \"__main__\":\n # spectral normalization does not work with TF2.0\n tf.disable_eager_execution()\n tf.app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Transport module.\"\"\"\n\n\nimport numpy as np\nfrom ravens import utils\nfrom ravens.models.resnet import ResNet43_8s\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\n\nclass Transport:\n \"\"\"Transport module.\"\"\"\n\n def __init__(self, in_shape, n_rotations, crop_size, preprocess):\n \"\"\"Transport module for placing.\n\n Args:\n in_shape: shape of input image.\n n_rotations: number of rotations of convolving kernel.\n crop_size: crop size around pick argmax used as convolving kernel.\n preprocess: function to preprocess input images.\n \"\"\"\n self.iters = 0\n self.n_rotations = n_rotations\n self.crop_size = crop_size # crop size must be N*16 (e.g. 96)\n self.preprocess = preprocess\n\n self.pad_size = int(self.crop_size / 2)\n self.padding = np.zeros((3, 2), dtype=int)\n self.padding[:2, :] = self.pad_size\n\n in_shape = np.array(in_shape)\n in_shape[0:2] += self.pad_size * 2\n in_shape = tuple(in_shape)\n\n # Crop before network (default for Transporters in CoRL submission).\n kernel_shape = (self.crop_size, self.crop_size, in_shape[2])\n\n if not hasattr(self, 'output_dim'):\n self.output_dim = 3\n if not hasattr(self, 'kernel_dim'):\n self.kernel_dim = 3\n\n # 2 fully convolutional ResNets with 57 layers and 16-stride\n in0, out0 = ResNet43_8s(in_shape, self.output_dim, prefix='s0_')\n # in1, out1 = ResNet43_8s(in_shape, self.kernel_dim, prefix='s1_')\n in1, out1 = ResNet43_8s(kernel_shape, self.kernel_dim, prefix='s1_')\n self.model = tf.keras.Model(inputs=[in0, in1], outputs=[out0, out1])\n self.optim = tf.keras.optimizers.Adam(learning_rate=1e-4)\n self.metric = tf.keras.metrics.Mean(name='loss_transport')\n\n # if not self.six_dof:\n # in0, out0 = ResNet43_8s(in_shape, output_dim, prefix=\"s0_\")\n # if self.crop_bef_q:\n # # Passing in kernels: (64,64,6) --> (64,64,3)\n # in1, out1 = ResNet43_8s(kernel_shape, kernel_dim, prefix=\"s1_\")\n # else:\n # # Passing in original images: (384,224,6) --> (394,224,3)\n # in1, out1 = ResNet43_8s(in_shape, output_dim, prefix=\"s1_\")\n # else:\n # in0, out0 = ResNet43_8s(in_shape, output_dim, prefix=\"s0_\")\n # # early cutoff just so it all fits on GPU.\n # in1, out1 = ResNet43_8s(\n # kernel_shape, kernel_dim, prefix=\"s1_\", cutoff_early=True)\n\n # def set_bounds_pixel_size(self, bounds, pixel_size):\n # self.bounds = bounds\n # self.pixel_size = pixel_size\n\n def correlate(self, in0, in1, softmax):\n \"\"\"Correlate two input tensors.\"\"\"\n output = tf.nn.convolution(in0, in1, data_format='NHWC')\n if softmax:\n output_shape = output.shape\n output = tf.reshape(output, (1, np.prod(output.shape)))\n output = tf.nn.softmax(output)\n output = np.float32(output).reshape(output_shape[1:])\n return output\n\n def forward(self, in_img, p, softmax=True):\n \"\"\"Forward pass.\"\"\"\n img_unprocessed = np.pad(in_img, self.padding, mode='constant')\n input_data = self.preprocess(img_unprocessed.copy())\n in_shape = (1,) + input_data.shape\n input_data = input_data.reshape(in_shape)\n in_tensor = tf.convert_to_tensor(input_data, dtype=tf.float32)\n\n # Rotate crop.\n pivot = np.array([p[1], p[0]]) + self.pad_size\n rvecs = self.get_se2(self.n_rotations, pivot)\n\n # Crop before network (default for Transporters in CoRL submission).\n crop = tf.convert_to_tensor(input_data.copy(), dtype=tf.float32)\n crop = tf.repeat(crop, repeats=self.n_rotations, axis=0)\n crop = tfa.image.transform(crop, rvecs, interpolation='NEAREST')\n crop = crop[:, p[0]:(p[0] + self.crop_size),\n p[1]:(p[1] + self.crop_size), :]\n logits, kernel_raw = self.model([in_tensor, crop])\n\n # Crop after network (for receptive field, and more elegant).\n # logits, crop = self.model([in_tensor, in_tensor])\n # # crop = tf.identity(kernel_bef_crop)\n # crop = tf.repeat(crop, repeats=self.n_rotations, axis=0)\n # crop = tfa.image.transform(crop, rvecs, interpolation='NEAREST')\n # kernel_raw = crop[:, p[0]:(p[0] + self.crop_size),\n # p[1]:(p[1] + self.crop_size), :]\n\n # Obtain kernels for cross-convolution.\n kernel_paddings = tf.constant([[0, 0], [0, 1], [0, 1], [0, 0]])\n kernel = tf.pad(kernel_raw, kernel_paddings, mode='CONSTANT')\n kernel = tf.transpose(kernel, [1, 2, 3, 0])\n\n return self.correlate(logits, kernel, softmax)\n\n def train(self, in_img, p, q, theta, backprop=True):\n \"\"\"Transport pixel p to pixel q.\n\n Args:\n in_img: input image.\n p: pixel (y, x)\n q: pixel (y, x)\n theta: rotation label in radians.\n backprop: True if backpropagating gradients.\n\n Returns:\n loss: training loss.\n \"\"\"\n\n self.metric.reset_states()\n with tf.GradientTape() as tape:\n output = self.forward(in_img, p, softmax=False)\n\n itheta = theta / (2 * np.pi / self.n_rotations)\n itheta = np.int32(np.round(itheta)) % self.n_rotations\n\n # Get one-hot pixel label map.\n label_size = in_img.shape[:2] + (self.n_rotations,)\n label = np.zeros(label_size)\n label[q[0], q[1], itheta] = 1\n\n # Get loss.\n label = label.reshape(1, np.prod(label.shape))\n label = tf.convert_to_tensor(label, dtype=tf.float32)\n output = tf.reshape(output, (1, np.prod(output.shape)))\n loss = tf.nn.softmax_cross_entropy_with_logits(label, output)\n loss = tf.reduce_mean(loss)\n\n if backprop:\n train_vars = self.model.trainable_variables\n grad = tape.gradient(loss, train_vars)\n self.optim.apply_gradients(zip(grad, train_vars))\n self.metric(loss)\n\n self.iters += 1\n return np.float32(loss)\n\n def get_se2(self, n_rotations, pivot):\n \"\"\"Get SE2 rotations discretized into n_rotations angles counter-clockwise.\"\"\"\n rvecs = []\n for i in range(n_rotations):\n theta = i * 2 * np.pi / n_rotations\n rmat = utils.get_image_transform(theta, (0, 0), pivot)\n rvec = rmat.reshape(-1)[:-1]\n rvecs.append(rvec)\n return np.array(rvecs, dtype=np.float32)\n\n def save(self, fname):\n self.model.save(fname)\n\n def load(self, fname):\n self.model.load_weights(fname)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n# pylint: disable=logging-format-interpolation\n# pylint: disable=unused-import\n# pylint: disable=g-long-lambda\n# pylint: disable=g-bare-generic\n# pylint: disable=g-complex-comprehension\n\nr\"\"\"AutoAugment and RandAugment policies for enhanced image preprocessing.\n\nAutoAugment Reference: https://arxiv.org/abs/1805.09501\nRandAugment Reference: https://arxiv.org/abs/1909.13719\n\"\"\"\n\nimport math\nfrom typing import Text, Dict, Any, Tuple, List\n\nfrom absl import logging\nimport tensorflow.compat.v1 as tf\n\nfrom tensorflow.contrib import image as image_ops\n\n\n# This signifies the max integer that the controller RNN could predict for the\n# augmentation scheme.\n_MAX_LEVEL = 10\n\n\nNAME_TO_FUNC = {\n 'AutoContrast': _autocontrast,\n 'Equalize': _equalize,\n 'Invert': _invert,\n 'Rotate': _rotate,\n 'Posterize': _posterize,\n 'Solarize': _solarize,\n 'SolarizeAdd': _solarize_add,\n 'Color': _color,\n 'Contrast': _contrast,\n 'Brightness': _brightness,\n 'Sharpness': _sharpness,\n 'ShearX': _shear_x,\n 'ShearY': _shear_y,\n 'TranslateX': _translate_x,\n 'TranslateY': _translate_y,\n 'Cutout': _cutout,\n 'Identity': _identity,\n}\n\n# Functions that have a 'replace' parameter\nREPLACE_FUNCS = frozenset({\n 'Rotate',\n 'TranslateX',\n 'ShearX',\n 'ShearY',\n 'TranslateY',\n 'Cutout',\n})\n\n\ndef blend(image1, image2, factor):\n \"\"\"Blend image1 and image2 using 'factor'.\n\n Factor can be above 0.0. A value of 0.0 means only image1 is used.\n A value of 1.0 means only image2 is used. A value between 0.0 and\n 1.0 means we linearly interpolate the pixel values between the two\n images. A value greater than 1.0 \"extrapolates\" the difference\n between the two pixel values, and we clip the results to values\n between 0 and 255.\n\n Args:\n image1: An image Tensor of type uint8.\n image2: An image Tensor of type uint8.\n factor: A floating point value above 0.0.\n\n Returns:\n A blended image Tensor of type uint8.\n \"\"\"\n def _blend():\n image_1 = tf.image.convert_image_dtype(image1, tf.float32)\n image_2 = tf.image.convert_image_dtype(image2, tf.float32)\n output = image_1 + factor * (image_2 - image_1)\n output = tf.where_v2(\n tf.logical_and(tf.less(0., factor), tf.less(factor, 1.)),\n x=output, y=tf.clip_by_value(output, 0., 255.))\n return tf.image.convert_image_dtype(output, tf.uint8)\n\n pred_fn_pairs = [\n (tf.equal(factor, 0.), lambda: image1),\n (tf.equal(factor, 1.), lambda: image2),\n ]\n return tf.case(\n pred_fn_pairs, default=_blend, exclusive=True, strict=True, name='blend')\n\n\ndef _cutout(image, pad_size, replace = 0):\n \"\"\"Apply cutout (https://arxiv.org/abs/1708.04552) to image.\n\n This operation applies a (2*pad_size x 2*pad_size) mask of zeros to\n a random location within `img`. The pixel values filled in will be of the\n value `replace`. The located where the mask will be applied is randomly\n chosen uniformly over the whole image.\n\n Args:\n image: An image Tensor of type uint8.\n pad_size: Specifies how big the zero mask that will be generated is that\n is applied to the image. The mask will be of size\n (2*pad_size x 2*pad_size).\n replace: What pixel value to fill in the image in the area that has\n the cutout mask applied to it.\n\n Returns:\n An image Tensor that is of type uint8.\n \"\"\"\n image_height = tf.shape(image)[0]\n image_width = tf.shape(image)[1]\n\n # Samples the center location in the image where the zero mask is applied.\n cutout_center_height = tf.random.uniform(\n shape=[], minval=0, maxval=image_height,\n dtype=tf.int32)\n\n cutout_center_width = tf.random.uniform(\n shape=[], minval=0, maxval=image_width,\n dtype=tf.int32)\n\n lower_pad = tf.maximum(0, cutout_center_height - pad_size)\n upper_pad = tf.maximum(0, image_height - cutout_center_height - pad_size)\n left_pad = tf.maximum(0, cutout_center_width - pad_size)\n right_pad = tf.maximum(0, image_width - cutout_center_width - pad_size)\n\n cutout_shape = [image_height - (lower_pad + upper_pad),\n image_width - (left_pad + right_pad)]\n padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]\n mask = tf.pad(\n tf.zeros(cutout_shape, dtype=image.dtype),\n padding_dims, constant_values=1)\n mask = tf.expand_dims(mask, -1)\n mask = tf.tile(mask, [1, 1, 3])\n image = tf.where_v2(\n tf.equal(mask, 0),\n tf.ones_like(image, dtype=image.dtype) * replace,\n image)\n return image\n\n\ndef _solarize(image, threshold = 128):\n \"\"\"Keep a pixel if `pixel < threshold`, otherwise subtract 225 from it.\"\"\"\n threshold = tf.cast(threshold, image.dtype)\n return tf.where_v2(image < threshold, image, 255 - image)\n\n\ndef _solarize_add(image,\n addition = 0,\n threshold = 128):\n \"\"\"If `pixel < threshold`, add `addition` to it and clip between 0 and 255.\"\"\"\n threshold = tf.cast(threshold, image.dtype)\n added_image = tf.cast(image, tf.int32) + addition\n added_image = tf.cast(tf.clip_by_value(added_image, 0, 255), tf.uint8)\n return tf.where_v2(image < threshold, added_image, image)\n\n\ndef _color(image, factor):\n \"\"\"Equivalent of PIL Color.\"\"\"\n degenerate = tf.image.grayscale_to_rgb(tf.image.rgb_to_grayscale(image))\n return blend(degenerate, image, factor)\n\n\ndef _contrast(image, factor):\n \"\"\"Equivalent of PIL Contrast.\"\"\"\n degenerate = tf.image.rgb_to_grayscale(image)\n # Cast before calling tf.histogram.\n degenerate = tf.cast(degenerate, tf.int32)\n\n # Compute the grayscale histogram, then compute the mean pixel value,\n # and create a constant image size of that value. Use that as the\n # blending degenerate target of the original image.\n hist = tf.histogram_fixed_width(degenerate, [0, 255], nbins=256)\n mean = tf.reduce_sum(tf.cast(hist, tf.float32)) / 256.0\n degenerate = tf.ones_like(degenerate, dtype=tf.float32) * mean\n degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)\n degenerate = tf.image.grayscale_to_rgb(tf.cast(degenerate, tf.uint8))\n return blend(degenerate, image, factor)\n\n\ndef _brightness(image, factor):\n \"\"\"Equivalent of PIL Brightness.\"\"\"\n degenerate = tf.zeros_like(image)\n return blend(degenerate, image, factor)\n\n\ndef _posterize(image, bits):\n \"\"\"Equivalent of PIL Posterize.\"\"\"\n shift = tf.cast(8 - bits, image.dtype)\n return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift)\n\n\ndef _rotate(image, degrees, replace):\n \"\"\"Rotates the image by degrees either clockwise or counterclockwise.\n\n Args:\n image: An image Tensor of type uint8.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n replace: A one or three value 1D tensor to fill empty pixels caused by\n the rotate operation.\n\n Returns:\n The rotated version of image.\n \"\"\"\n # Convert from degrees to radians.\n degrees_to_radians = math.pi / 180.0\n radians = degrees * degrees_to_radians\n\n # In practice, we should randomize the rotation degrees by flipping\n # it negatively half the time, but that's done on 'degrees' outside\n # of the function.\n image = image_ops.rotate(_wrap(image), radians)\n return _unwrap(image, replace)\n\n\ndef _translate_x(image, pixels, replace):\n \"\"\"Equivalent of PIL Translate in X dimension.\"\"\"\n image = image_ops.translate(_wrap(image), [-pixels, 0])\n return _unwrap(image, replace)\n\n\ndef _translate_y(image, pixels, replace):\n \"\"\"Equivalent of PIL Translate in Y dimension.\"\"\"\n image = image_ops.translate(_wrap(image), [0, -pixels])\n return _unwrap(image, replace)\n\n\ndef _shear_x(image, level, replace):\n \"\"\"Equivalent of PIL Shearing in X dimension.\"\"\"\n # Shear parallel to x axis is a projective transform\n # with a matrix form of:\n # [1 level\n # 0 1].\n image = image_ops.transform(\n _wrap(image), [1., level, 0., 0., 1., 0., 0., 0.])\n return _unwrap(image, replace)\n\n\ndef _shear_y(image, level, replace):\n \"\"\"Equivalent of PIL Shearing in Y dimension.\"\"\"\n # Shear parallel to y axis is a projective transform\n # with a matrix form of:\n # [1 0\n # level 1].\n image = image_ops.transform(\n _wrap(image), [1., 0., 0., level, 1., 0., 0., 0.])\n return _unwrap(image, replace)\n\n\ndef _identity(image):\n \"\"\"Identity.\"\"\"\n return tf.identity(image)\n\n\ndef _autocontrast(image):\n \"\"\"Implements Autocontrast function from PIL using TF ops.\n\n Args:\n image: A 3D uint8 tensor.\n\n Returns:\n The image after it has had autocontrast applied to it and will be of type\n uint8.\n \"\"\"\n\n def scale_channel(image):\n \"\"\"Scale the 2D image using the autocontrast rule.\"\"\"\n # A possibly cheaper version can be done using cumsum/unique_with_counts\n # over the histogram values, rather than iterating over the entire image.\n # to compute mins and maxes.\n lo = tf.cast(tf.reduce_min(image), tf.float32)\n hi = tf.cast(tf.reduce_max(image), tf.float32)\n\n # Scale the image, making the lowest value 0 and the highest value 255.\n def scale_values(im):\n scale = 255.0 / (hi - lo)\n offset = -lo * scale\n im = tf.cast(im, tf.float32) * scale + offset\n im = tf.clip_by_value(im, 0.0, 255.0)\n return tf.cast(im, tf.uint8)\n\n result = tf.cond(hi > lo, lambda: scale_values(image), lambda: image)\n return result\n\n # Assumes RGB for now. Scales each channel independently\n # and then stacks the result.\n s1 = scale_channel(image[:, :, 0])\n s2 = scale_channel(image[:, :, 1])\n s3 = scale_channel(image[:, :, 2])\n image = tf.stack([s1, s2, s3], 2)\n return image\n\n\ndef _sharpness(image, factor):\n \"\"\"Implements Sharpness function from PIL using TF ops.\"\"\"\n orig_image = image\n image = tf.cast(image, tf.float32)\n # Make image 4D for conv operation.\n image = tf.expand_dims(image, 0)\n # SMOOTH PIL Kernel.\n kernel = tf.constant(\n [[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=tf.float32,\n shape=[3, 3, 1, 1]) / 13.\n # Tile across channel dimension.\n kernel = tf.tile(kernel, [1, 1, 3, 1])\n strides = [1, 1, 1, 1]\n degenerate = tf.nn.depthwise_conv2d(\n image, kernel, strides, padding='VALID', dilations=[1, 1])\n degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)\n degenerate = tf.squeeze(tf.cast(degenerate, tf.uint8), [0])\n\n # For the borders of the resulting image, fill in the values of the\n # original image.\n mask = tf.ones_like(degenerate)\n padded_mask = tf.pad(mask, [[1, 1], [1, 1], [0, 0]])\n padded_degenerate = tf.pad(degenerate, [[1, 1], [1, 1], [0, 0]])\n result = tf.where_v2(tf.equal(padded_mask, 1), padded_degenerate, orig_image)\n\n # Blend the final result.\n return blend(result, orig_image, factor)\n\n\ndef _equalize(image):\n \"\"\"Implements Equalize function from PIL using TF ops.\"\"\"\n def scale_channel(im, c):\n \"\"\"Scale the data in the channel to implement equalize.\"\"\"\n im = tf.cast(im[:, :, c], tf.int32)\n # Compute the histogram of the image channel.\n histo = tf.histogram_fixed_width(im, [0, 255], nbins=256)\n\n # For the purposes of computing the step, filter out the nonzeros.\n nonzero = tf.where_v2(tf.not_equal(histo, 0))\n nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [-1])\n step = (tf.reduce_sum(nonzero_histo) - nonzero_histo[-1]) // 255\n\n def build_lut(histo, step):\n # Compute the cumulative sum, shifting by step // 2\n # and then normalization by step.\n lut = (tf.cumsum(histo) + (step // 2)) // step\n # Shift lut, prepending with 0.\n lut = tf.concat([[0], lut[:-1]], 0)\n # Clip the counts to be in range. This is done\n # in the C code for image.point.\n return tf.clip_by_value(lut, 0, 255)\n\n # If step is zero, return the original image. Otherwise, build\n # lut from the full histogram and step and then index from it.\n result = tf.cond(tf.equal(step, 0),\n lambda: im,\n lambda: tf.gather(build_lut(histo, step), im))\n\n return tf.cast(result, tf.uint8)\n\n # Assumes RGB for now. Scales each channel independently\n # and then stacks the result.\n s1 = scale_channel(image, 0)\n s2 = scale_channel(image, 1)\n s3 = scale_channel(image, 2)\n image = tf.stack([s1, s2, s3], 2)\n return image\n\n\ndef _invert(image):\n \"\"\"Inverts the image pixels.\"\"\"\n image = tf.convert_to_tensor(image)\n return 255 - image\n\n\ndef _wrap(image):\n \"\"\"Returns 'image' with an extra channel set to all 1s.\"\"\"\n shape = tf.shape(image)\n extended_channel = tf.ones([shape[0], shape[1], 1], image.dtype)\n extended = tf.concat([image, extended_channel], axis=2)\n return extended\n\n\ndef _unwrap(image, replace):\n \"\"\"_unwraps an image produced by _wrap.\n\n Where there is a 0 in the last channel for every spatial position,\n the rest of the three channels in that spatial dimension are grayed\n (set to 128). Operations like translate and shear on a _wrapped\n Tensor will leave 0s in empty locations. Some transformations look\n at the intensity of values to do preprocessing, and we want these\n empty pixels to assume the 'average' value, rather than pure black.\n\n\n Args:\n image: A 3D Image Tensor with 4 channels.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n image: A 3D image Tensor with 3 channels.\n \"\"\"\n image_shape = tf.shape(image)\n # Flatten the spatial dimensions.\n flattened_image = tf.reshape(image, [-1, image_shape[2]])\n\n # Find all pixels where the last channel is zero.\n alpha_channel = tf.expand_dims(flattened_image[:, 3], axis=-1)\n alpha_channel = tf.tile(alpha_channel, [1, 4])\n\n replace = tf.concat([replace, tf.ones([1], image.dtype)], 0)\n\n # Where they are zero, fill them in with 'replace'.\n flattened_image = tf.where_v2(\n tf.equal(alpha_channel, 0),\n tf.ones_like(flattened_image, dtype=image.dtype) * replace,\n flattened_image)\n\n image = tf.reshape(flattened_image, image_shape)\n image = tf.slice(image, [0, 0, 0], [image_shape[0], image_shape[1], 3])\n return image\n\n\ndef _randomly_negate_tensor(tensor):\n \"\"\"With 50% prob turn the tensor negative.\"\"\"\n should_flip = tf.cast(tf.floor(tf.random.uniform([]) + 0.5), tf.bool)\n final_tensor = tf.cond(should_flip, lambda: tensor, lambda: -tensor)\n return final_tensor\n\n\ndef _rotate__level_to_arg(level):\n level = (level/_MAX_LEVEL) * 30.\n level = _randomly_negate_tensor(level)\n return (level,)\n\n\ndef _shrink__level_to_arg(level):\n \"\"\"Converts level to ratio by which we shrink the image content.\"\"\"\n return tf.cond(\n tf.equal(level, 0.), lambda: 1., lambda: 2. / (_MAX_LEVEL / level) + 0.9)\n\n\ndef _enhance__level_to_arg(level):\n return ((level/_MAX_LEVEL) * 1.8 + 0.1,)\n\n\ndef _shear__level_to_arg(level):\n level = (level/_MAX_LEVEL) * 0.3\n # Flip level to negative with 50% chance.\n level = _randomly_negate_tensor(level)\n return (level,)\n\n\ndef _translate__level_to_arg(level, translate_const):\n level = (level/_MAX_LEVEL) * float(translate_const)\n # Flip level to negative with 50% chance.\n level = _randomly_negate_tensor(level)\n return (level,)\n\n\ndef _mult_to_arg(level, multiplier = 1.):\n # return (int(float(level) / _MAX_LEVEL * multiplier),)\n return (\n tf.cast(tf.cast(level, tf.float32) / _MAX_LEVEL * multiplier, tf.int32),)\n\n\ndef _apply_func_with_prob(func,\n image,\n args,\n prob):\n \"\"\"Apply `func` to image w/ `args` as input with probability `prob`.\"\"\"\n assert isinstance(args, tuple)\n\n # Apply the function with probability `prob`.\n should_apply_op = tf.cast(\n tf.floor(tf.random.uniform([], dtype=tf.float32) + prob), tf.bool)\n augmented_image = tf.cond(\n should_apply_op,\n lambda: func(image, *args),\n lambda: image)\n return augmented_image\n\n\ndef _select_and_apply_random_policy(policies, image):\n \"\"\"Select a random policy from `policies` and apply it to `image`.\"\"\"\n policy_to_select = tf.random.uniform([], maxval=len(policies), dtype=tf.int32)\n # Note that using tf.case instead of tf.conds would result in significantly\n # larger graphs and would even break export for some larger policies.\n for (i, policy) in enumerate(policies):\n image = tf.cond(\n tf.equal(i, policy_to_select),\n lambda selected_policy=policy: selected_policy(image),\n lambda: image)\n return image\n\n\ndef _level_to_arg(cutout_const, translate_const):\n \"\"\"Creates a dict mapping image operation names to their arguments.\"\"\"\n\n no_arg = lambda level: ()\n posterize_arg = lambda level: _mult_to_arg(level, 4)\n solarize_arg = lambda level: _mult_to_arg(level, 256)\n solarize_add_arg = lambda level: _mult_to_arg(level, 110)\n cutout_arg = lambda level: _mult_to_arg(level, cutout_const)\n translate_arg = lambda level: _translate__level_to_arg(level, translate_const)\n\n args = {\n 'Identity': no_arg,\n 'AutoContrast': no_arg,\n 'Equalize': no_arg,\n 'Invert': no_arg,\n 'Rotate': _rotate__level_to_arg,\n 'Posterize': posterize_arg,\n 'Solarize': solarize_arg,\n 'SolarizeAdd': solarize_add_arg,\n 'Color': _enhance__level_to_arg,\n 'Contrast': _enhance__level_to_arg,\n 'Brightness': _enhance__level_to_arg,\n 'Sharpness': _enhance__level_to_arg,\n 'ShearX': _shear__level_to_arg,\n 'ShearY': _shear__level_to_arg,\n 'Cutout': cutout_arg,\n 'TranslateX': translate_arg,\n 'TranslateY': translate_arg,\n }\n return args\n\n\ndef _parse_policy_info(name,\n prob,\n level,\n replace_value,\n cutout_const,\n translate_const):\n \"\"\"Return the function that corresponds to `name` and update `level` param.\"\"\"\n func = NAME_TO_FUNC[name]\n args = _level_to_arg(cutout_const, translate_const)[name](level)\n\n if name in REPLACE_FUNCS:\n # Add in replace arg if it is required for the function that is called.\n args = tuple(list(args) + [replace_value])\n\n return func, prob, args\n\n\nclass ImageAugment(object):\n \"\"\"Image augmentation class for applying image distortions.\"\"\"\n\n def distort(self, image):\n \"\"\"Given an image tensor, returns a distorted image with the same shape.\n\n Args:\n image: `Tensor` of shape [height, width, 3] representing an image.\n\n Returns:\n The augmented version of `image`.\n \"\"\"\n raise NotImplementedError()\n\n\nclass RandAugment(ImageAugment):\n \"\"\"Applies the RandAugment policy to images.\n\n RandAugment is from the paper https://arxiv.org/abs/1909.13719,\n \"\"\"\n\n def __init__(self,\n num_layers = 2,\n magnitude = None,\n cutout_const = 40.,\n translate_const = 100.,\n available_ops = None):\n \"\"\"Applies the RandAugment policy to images.\n\n Args:\n num_layers: Integer, the number of augmentation transformations to apply\n sequentially to an image. Represented as (N) in the paper. Usually best\n values will be in the range [1, 3].\n magnitude: Integer, shared magnitude across all augmentation operations.\n Represented as (M) in the paper. Usually best values are in the range\n [5, 30].\n cutout_const: multiplier for applying cutout.\n translate_const: multiplier for applying translation.\n available_ops: allow to override the default option of using all ops.\n \"\"\"\n super(RandAugment, self).__init__()\n\n self.num_layers = num_layers\n self.cutout_const = float(cutout_const)\n self.translate_const = float(translate_const)\n if available_ops is None:\n available_ops = [\n 'AutoContrast', 'Equalize', 'Invert', 'Rotate', 'Posterize',\n 'Solarize', 'Color', 'Contrast', 'Brightness', 'Sharpness',\n 'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Cutout',\n ]\n self.available_ops = available_ops\n self.magnitude = magnitude\n\n def distort(self, image):\n \"\"\"Applies the RandAugment policy to `image`.\n\n Args:\n image: `Tensor` of shape `h, w, 3` representing an image.\n\n Returns:\n The augmented version of `image`.\n \"\"\"\n input_image_type = image.dtype\n image = tf.clip_by_value(\n image, tf.cast(0, image.dtype), tf.cast(255, image.dtype))\n image = tf.cast(image, dtype=tf.uint8)\n\n replace_value = [128] * 3\n prob = tf.random.uniform([], 0.2, 0.8, tf.float32)\n for _ in range(self.num_layers):\n op_to_select = tf.random.uniform(\n [], minval=0, maxval=len(self.available_ops), dtype=tf.int32)\n\n branch_fns = []\n for (i, op_name) in enumerate(self.available_ops):\n func, _, args = _parse_policy_info(op_name, prob, self.magnitude,\n replace_value, self.cutout_const,\n self.translate_const)\n def branch_fn(selected_func=func, selected_args=args):\n return tf.cond(tf.random.uniform([], 0., 1., prob.dtype) <= prob,\n lambda: selected_func(image, *selected_args),\n lambda: image)\n branch_fns.append((i, branch_fn))\n\n image = tf.switch_case(branch_index=op_to_select, branch_fns=branch_fns)\n\n image = tf.cast(image, dtype=input_image_type)\n return image\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Gym wrapper environments for reset-free learning.\n\nThe environment retains its old state, but goals/tasks can be changed during the\nepisode.\n\"\"\"\n\nfrom gym import Wrapper\nimport tensorflow as tf\n\n\nclass ResetFreeWrapper(Wrapper):\n\n def __init__(self,\n env,\n reset_goal_frequency,\n variable_horizon_for_reset=False,\n num_success_states=1,\n full_reset_frequency=None,\n reset_goal_fn=None):\n\n super(ResetFreeWrapper, self).__init__(env)\n self._rfw_step_count = 0\n self._virtual_episode_steps = 0\n self._goal_switch = False\n self._reset_goal_frequency = reset_goal_frequency\n self._variable_horizon_for_reset = variable_horizon_for_reset\n self._num_success_states = num_success_states\n self._full_reset_frequency = full_reset_frequency\n self._reset_goal_fn = reset_goal_fn\n self._reset_state_candidates = None\n self._forward_or_reset_goal = True # True -> forward, False -> reset goal\n self._goal_queue = []\n\n def reset(self):\n # variable resets\n if self._variable_horizon_for_reset:\n self._success_state_seq_length = 0\n self._virtual_episode_steps = 0\n\n if self._goal_switch:\n if self._reset_goal_fn is None or self._reset_state_candidates is None:\n self.env.reset_goal()\n self._forward_or_reset_goal = True\n else:\n if not self._goal_queue:\n self._forward_or_reset_goal = False\n next_task_goal = self.env.get_next_goal()\n self._goal_queue = [next_task_goal] + self._goal_queue\n reset_goal = self._reset_goal_fn(\n self._reset_state_candidates,\n tf.constant(self.env._get_obs(), dtype=tf.float32),\n tf.constant(next_task_goal, dtype=tf.float32))\n\n if isinstance(reset_goal, tf.Tensor):\n reset_goal = reset_goal.numpy()\n\n self.env.reset_goal(goal=reset_goal)\n else:\n self._forward_or_reset_goal = True\n next_task_goal = self._goal_queue.pop()\n self.env.reset_goal(goal=next_task_goal)\n\n self._goal_switch = False\n return self.env._get_obs()\n else:\n self._forward_or_reset_goal = True\n return self.env.reset()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(\n action) # always check if the underneath env is done\n\n self._rfw_step_count += 1\n self._virtual_episode_steps += 1\n\n # a full reset including robot arm and objects\n if not done and self._full_reset_frequency is not None and self._rfw_step_count % self._full_reset_frequency == 0:\n done = True\n\n # finishes the episode and reset the goal, but no change in env state\n if not done and self._virtual_episode_steps % self._reset_goal_frequency == 0:\n done = True\n self._goal_switch = True\n\n # only have variable horizon for reset goals\n # switch to forward goal when reset state has been achieved for a bit\n if self._variable_horizon_for_reset and not done and not self._forward_or_reset_goal:\n if self.env.is_successful():\n self._success_state_seq_length += 1\n else:\n self._success_state_seq_length = 0\n if self._success_state_seq_length >= self._num_success_states:\n done = True\n self._goal_switch = True\n\n return obs, reward, done, info\n\n def set_reset_goal_fn(self, reset_goal_fn):\n self._reset_goal_fn = reset_goal_fn\n\n # it is not possible to sample the replay buffer while the data is being\n # collected, therefore we have to lazily update the reset candidates.\n def set_reset_candidates(self, reset_candidates):\n self._reset_state_candidates = reset_candidates\n\n\nclass CustomOracleResetWrapper(Wrapper):\n\n def __init__(self,\n env,\n partial_reset_frequency,\n episodes_before_full_reset,\n reset_goal_fn=None):\n\n super(CustomOracleResetWrapper, self).__init__(env)\n self._rfw_step_count = 0\n self._partial_reset_frequency = partial_reset_frequency\n self._episodes_before_full_reset = episodes_before_full_reset\n self._episode_count = -1\n self._reset_goal_fn = reset_goal_fn\n self._reset_state_candidates = None\n\n def reset(self):\n self._episode_count += 1\n if self._episode_count % self._episodes_before_full_reset == 0:\n return self.env.reset()\n elif self._reset_state_candidates is not None:\n next_task_goal = self.env.get_next_goal()\n obs_before_teleporting = self.env._get_obs()\n reset_goal = self._reset_goal_fn(\n self._reset_state_candidates,\n tf.constant(obs_before_teleporting, dtype=tf.float32),\n tf.constant(next_task_goal, dtype=tf.float32))\n if isinstance(reset_goal, tf.Tensor):\n reset_goal = reset_goal.numpy()\n self.env.do_custom_reset(pos=reset_goal)\n self.env.reset()\n self.env.reset_goal(\n goal=next_task_goal\n ) # otherwise the reset state would be for the wrong goal\n return self.env._get_obs()\n else:\n return self.env.reset()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(\n action) # always check if the underneath env is done\n\n self._rfw_step_count += 1\n\n # a full reset including robot arm and objects\n if not done and self._rfw_step_count % self._partial_reset_frequency == 0:\n done = True\n\n return obs, reward, done, info\n\n def set_reset_goal_fn(self, reset_goal_fn):\n self._reset_goal_fn = reset_goal_fn\n\n # it is not possible to sample the replay buffer while the data is being\n # collected, therefore we have to lazily update the reset candidates.\n def set_reset_candidates(self, reset_candidates):\n self._reset_state_candidates = reset_candidates\n\n\nclass GoalTerminalResetFreeWrapper(Wrapper):\n\n def __init__(self,\n env,\n reset_goal_frequency,\n num_success_states=1,\n full_reset_frequency=None,\n reset_goal_fn=None):\n\n super(GoalTerminalResetFreeWrapper, self).__init__(env)\n self._rfw_step_count = 0\n self._virtual_episode_steps = 0\n self._goal_switch = False\n self._reset_goal_frequency = reset_goal_frequency\n self._num_success_states = num_success_states\n self._full_reset_frequency = full_reset_frequency\n self._reset_goal_fn = reset_goal_fn\n self._reset_state_candidates = None\n self._forward_or_reset_goal = True # True -> forward, False -> reset goal\n self._goal_queue = []\n\n def reset(self):\n self._success_state_seq_length = 0\n self._virtual_episode_steps = 0\n\n if self._goal_switch:\n if self._reset_goal_fn is None:\n self.env.reset_goal()\n self._forward_or_reset_goal = True\n else:\n if not self._goal_queue:\n self._forward_or_reset_goal = False\n next_task_goal = self.env.get_next_goal()\n self._goal_queue = [next_task_goal] + self._goal_queue\n reset_goal = self._reset_goal_fn(\n self._reset_state_candidates,\n tf.constant(self.env._get_obs(), dtype=tf.float32),\n tf.constant(next_task_goal, dtype=tf.float32))\n\n if isinstance(reset_goal, tf.Tensor):\n reset_goal = reset_goal.numpy()\n\n self.env.reset_goal(goal=reset_goal)\n else:\n self._forward_or_reset_goal = True\n next_task_goal = self._goal_queue.pop()\n self.env.reset_goal(goal=next_task_goal)\n\n self._goal_switch = False\n return self.env._get_obs()\n else:\n self._forward_or_reset_goal = True\n return self.env.reset()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(\n action) # always check if the underneath env is done\n\n self._rfw_step_count += 1\n self._virtual_episode_steps += 1\n\n # a full reset including robot arm and objects\n if not done and self._full_reset_frequency is not None and self._rfw_step_count % self._full_reset_frequency == 0:\n done = True\n\n # finishes the episode and reset the goal, but no change in env state\n if not done and self._virtual_episode_steps % self._reset_goal_frequency == 0:\n done = True\n self._goal_switch = True\n\n # reset goal whenever the goal state is achieved\n if not done:\n if self.env.is_successful():\n self._success_state_seq_length += 1\n else:\n self._success_state_seq_length = 0\n if self._success_state_seq_length >= self._num_success_states:\n done = True\n self._goal_switch = True\n\n return obs, reward, done, info\n\n def set_reset_goal_fn(self, reset_goal_fn):\n self._reset_goal_fn = reset_goal_fn\n\n # it is not possible to sample the replay buffer while the data is being\n # collected, therefore we have to lazily update the reset candidates.\n def set_reset_candidates(self, reset_candidates):\n self._reset_state_candidates = reset_candidates\n\n\nclass GoalTerminalResetWrapper(Wrapper):\n\n def __init__(self, env, num_success_states=1, full_reset_frequency=None):\n\n super(GoalTerminalResetWrapper, self).__init__(env)\n self._virtual_episode_steps = 0\n self._num_success_states = num_success_states\n self._full_reset_frequency = full_reset_frequency\n self._goal_queue = []\n\n def reset(self):\n self._success_state_seq_length = 0\n self._virtual_episode_steps = 0\n\n return self.env.reset()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(\n action) # always check if the underneath env is done\n\n self._virtual_episode_steps += 1\n\n # finishes the episode and resets the environment\n if not done and self._virtual_episode_steps % self._full_reset_frequency == 0:\n done = True\n\n # reset whenever the goal state is achieved\n if not done and hasattr(self.env, 'is_successful'):\n if self.env.is_successful():\n self._success_state_seq_length += 1\n else:\n self._success_state_seq_length = 0\n if self._success_state_seq_length >= self._num_success_states:\n done = True\n\n return obs, reward, done, info\n\n\nclass CustomOracleResetGoalTerminalWrapper(Wrapper):\n\n def __init__(self,\n env,\n partial_reset_frequency,\n episodes_before_full_reset,\n reset_goal_fn=None):\n\n super(CustomOracleResetGoalTerminalWrapper, self).__init__(env)\n self._rfw_step_count = 0\n self._virtual_episode_steps = 0\n self._partial_reset_frequency = partial_reset_frequency\n self._episodes_before_full_reset = episodes_before_full_reset\n self._episode_count = -1\n self._reset_goal_fn = reset_goal_fn\n self._reset_state_candidates = None\n\n def reset(self):\n self._virtual_episode_steps = 0\n self._episode_count += 1\n if self._episode_count % self._episodes_before_full_reset == 0:\n return self.env.reset()\n\n elif self._reset_state_candidates is not None:\n next_task_goal = self.env.get_next_goal()\n obs_before_teleporting = self.env._get_obs()\n reset_goal = self._reset_goal_fn(\n self._reset_state_candidates,\n tf.constant(obs_before_teleporting, dtype=tf.float32),\n tf.constant(next_task_goal, dtype=tf.float32))\n if isinstance(reset_goal, tf.Tensor):\n reset_goal = reset_goal.numpy()\n self.env.do_custom_reset(pos=reset_goal)\n self.env.reset()\n self.env.reset_goal(\n goal=next_task_goal\n ) # otherwise the reset state would be for the wrong goal\n return self.env._get_obs()\n else:\n return self.env.reset()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(\n action) # always check if the underneath env is done\n\n self._rfw_step_count += 1\n self._virtual_episode_steps += 1\n\n # a full reset including robot arm and objects\n if not done and self._virtual_episode_steps % self._partial_reset_frequency == 0:\n done = True\n\n # reset whenever the goal state is achieved\n if not done and self.env.is_successful():\n done = True\n\n return obs, reward, done, info\n\n def set_reset_goal_fn(self, reset_goal_fn):\n self._reset_goal_fn = reset_goal_fn\n\n # it is not possible to sample the replay buffer while the data is being\n # collected, therefore we have to lazily update the reset candidates.\n def set_reset_candidates(self, reset_candidates):\n self._reset_state_candidates = reset_candidates\n\n\nclass VariableGoalTerminalResetWrapper(Wrapper):\n\n def __init__(self,\n env,\n num_success_states=1,\n full_reset_frequency=None,\n reset_goal_fn=None):\n\n super(VariableGoalTerminalResetWrapper, self).__init__(env)\n self._virtual_episode_steps = 0\n self._num_success_states = num_success_states\n self._full_reset_frequency = full_reset_frequency\n self._goal_queue = []\n self._reset_goal_fn = reset_goal_fn\n self._reset_state_candidates = None\n\n def reset(self):\n self._success_state_seq_length = 0\n self._virtual_episode_steps = 0\n\n # NOTE: assuming we are resetting at the goal\n if self._reset_goal_fn is not None:\n next_task_goal = self.env.get_next_goal()\n obs_before_teleporting = self.env._get_obs()\n reset_goal = self._reset_goal_fn(\n self._reset_state_candidates,\n tf.constant(obs_before_teleporting, dtype=tf.float32),\n tf.constant(next_task_goal, dtype=tf.float32))\n if isinstance(reset_goal, tf.Tensor):\n reset_goal = reset_goal.numpy()\n self.env.reset()\n self.env.reset_goal(\n goal=reset_goal\n ) # otherwise the reset state would be for the wrong goal\n return self.env._get_obs()\n else:\n reset_obs = self.env.reset()\n\n return reset_obs\n\n def step(self, action):\n obs, reward, done, info = self.env.step(\n action) # always check if the underneath env is done\n\n self._virtual_episode_steps += 1\n\n # finishes the episode and resets the environment\n if not done and self._virtual_episode_steps % self._full_reset_frequency == 0:\n done = True\n\n # reset whenever the goal state is achieved\n if not done:\n if self.env.is_successful():\n self._success_state_seq_length += 1\n else:\n self._success_state_seq_length = 0\n if self._success_state_seq_length >= self._num_success_states:\n done = True\n\n return obs, reward, done, info\n\n def set_reset_goal_fn(self, reset_goal_fn):\n self._reset_goal_fn = reset_goal_fn\n\n # it is not possible to sample the replay buffer while the data is being\n # collected, therefore we have to lazily update the reset candidates.\n def set_reset_candidates(self, reset_candidates):\n self._reset_state_candidates = reset_candidates\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"scVI run and evaluation.\n\nRuns scVI with the specified input parameters and evaluates it.\n\nThis is a weird 'hack' that launches a hyperparameter grid locally\nbecause our grid is so large that we cannot launch one configuration\nper machine.\n\"\"\"\n\nimport collections\nimport csv\nimport itertools\nimport os\nimport random\nimport tempfile\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport anndata\nimport numpy as np\nimport scanpy.api as sc\nimport scvi\nimport scvi.dataset\nimport scvi.inference\nimport sklearn.cluster\nimport sklearn.metrics\nimport tensorflow as tf\nimport torch\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('input_path', None,\n 'Path to the input loom or anndata file.')\nflags.DEFINE_string('output_csv', None,\n 'Path to the folder containing the csv results.')\nflags.DEFINE_string('log_path', None,\n 'Path to the folder containing the runs log.')\nflags.DEFINE_integer(\n 'seed', None,\n 'Random seed to use in the run. If no value is given we will run for 1..5')\n\n# Flags about the scVI run hyperparameters.\nflags.DEFINE_integer(\n 'n_layers', None, 'Number of hidden layers used for encoder and '\n 'decoder NNs')\nflags.DEFINE_integer('n_hidden', None, 'Number of nodes per hidden layer')\nflags.DEFINE_enum('dispersion', None, ['gene', 'gene-cell'],\n 'What kind of dispersion to use.')\nflags.DEFINE_float('dropout_rate', None, 'Dropout rate for neural networks')\nflags.DEFINE_enum('reconstruction_loss', None, ['zinb', 'nb'],\n 'Generative distribution.')\nflags.DEFINE_integer(\n 'n_latent', None,\n 'Dimensionality of the latent space. If no value is given, it will run for '\n '2, 8, 10, 16, 32, 50, 64, and 128.')\nflags.DEFINE_integer(\n 'epochs', None,\n 'Number of epochs to train on. If no value is given, it will run for '\n '20, 50, 100, 200, 300, 500, and 1000.')\nflags.DEFINE_float(\n 'lr', None,\n 'Learning rate. If no value is given, it will run for 1e-2, 1e-3, and 1e-4.'\n)\n\n# Flags about the environment the code is executed in and its output.\nflags.DEFINE_boolean('from_gcs', True, 'Whether the input is hosted on GCS.')\nflags.DEFINE_boolean('save_h5ad', False, 'Whether the anndata should be saved.')\nflags.DEFINE_boolean('seurat_readable', False,\n 'Whether to make the file Seurat readable.')\n\nConf = collections.namedtuple('Conf', ['n_latent', 'epochs', 'lr', 'seed'])\nMetrics = collections.namedtuple(\n 'Metrics', ['silhouette', 'kmeans_silhouette', 'ami', 'ari'])\nRunResult = collections.namedtuple('RunResult', [\n 'method', 'seed', 'n_layers', 'n_hidden', 'dispersion', 'dropout_rate',\n 'reconstruction_loss', 'n_latent', 'epochs', 'lr', 'silhouette',\n 'kmeans_silhouette', 'kmeans_ami', 'kmeans_ari', 'n_cells', 'tissue',\n 'n_clusters', 'elbo_train_set', 'elbo_test_set', 'h5ad_fname'\n])\n\n\ndef evaluate_method(adata, n_clusters):\n \"\"\"Runs the AMI, ARI, and silhouette computation.\"\"\"\n # If the training diverged, the embedding will have nan for infinity.\n if np.any(np.isnan(adata.obsm['X_scvi'])):\n return Metrics(\n silhouette=float('nan'),\n kmeans_silhouette=float('nan'),\n ari=float('nan'),\n ami=float('nan'),\n )\n\n silhouette = sklearn.metrics.silhouette_score(adata.obsm['X_scvi'],\n adata.obs['label'])\n\n kmeans = sklearn.cluster.KMeans(\n n_clusters=n_clusters, random_state=0).fit(adata.obsm['X_scvi'])\n adata.obs['predicted_clusters'] = kmeans.labels_\n\n # If all kmeans clusters end up together (failure to converge), the silhouette\n # computation will crash.\n if len(np.unique(adata.obs['predicted_clusters'])) < 2:\n kmeans_silhouette = float('nan')\n else:\n kmeans_silhouette = sklearn.metrics.silhouette_score(\n adata.obsm['X_scvi'], adata.obs['predicted_clusters'])\n ari = sklearn.metrics.adjusted_rand_score(adata.obs['label'],\n adata.obs['predicted_clusters'])\n ami = sklearn.metrics.adjusted_mutual_info_score(\n adata.obs['label'], adata.obs['predicted_clusters'])\n\n return Metrics(\n silhouette=silhouette,\n kmeans_silhouette=kmeans_silhouette,\n ami=ami,\n ari=ari)\n\n\ndef compute_scvi_latent(scvi_dataset,\n n_latent,\n n_layers,\n n_hidden,\n dropout_rate,\n dispersion,\n reconstruction_loss,\n n_epochs,\n lr,\n use_batches=False,\n use_cuda=True):\n \"\"\"Train and return a scVI latent space.\n\n Args:\n scvi_dataset: dataset.GeneExpressionDataset to work on.\n n_latent: Dimensionality of the latent space.\n n_layers: Number of hidden layers used for encoder and decoder NNs.\n n_hidden: Number of nodes per hidden layer.\n dropout_rate: Dropout rate for neural networks.\n dispersion: One of the following * 'gene' - dispersion parameter of NB is\n constant per gene across cells * 'gene-batch' - dispersion can differ\n between different batches * 'gene-label' - dispersion can differ between\n different labels * 'gene-cell' - dispersion can differ for every gene in\n every cell.\n reconstruction_loss: One of * 'nb' - Negative Binomial distribution. *\n 'zinb' - Zero-Inflated Negative Binomial distribution.\n n_epochs: int, number of epochs to run, default 100.\n lr: float, learning rate, default 1e-3.\n use_batches: bool, whether to apply batch correction.\n use_cuda: bool, whether to use CUDA if available.\n\n Returns:\n latent: a numpy array with cooordiantes in the latent space.\n elbo_train_set: list of the ELBO on the train set.\n elbo_test_set: list of the ELBO on the test set.\n \"\"\"\n\n # Train a model.\n vae = scvi.models.VAE(\n n_input=scvi_dataset.nb_genes,\n n_batch=scvi_dataset.n_batches * use_batches,\n n_latent=n_latent,\n n_layers=n_layers,\n n_hidden=n_hidden,\n dropout_rate=dropout_rate,\n dispersion=dispersion,\n reconstruction_loss=reconstruction_loss,\n )\n trainer = scvi.inference.UnsupervisedTrainer(\n vae, scvi_dataset, train_size=0.8, use_cuda=use_cuda, frequency=5)\n trainer.train(n_epochs=n_epochs, lr=lr)\n\n elbo_train_set = trainer.history['elbo_train_set']\n elbo_test_set = trainer.history['elbo_test_set']\n\n # Extract latent space\n posterior = trainer.create_posterior(\n trainer.model, scvi_dataset,\n indices=np.arange(len(scvi_dataset))).sequential()\n\n latent, _, _ = posterior.get_latent()\n\n return latent, elbo_train_set, elbo_test_set\n\n\ndef log_run(path, conf):\n \"\"\"Logs a successful run in a CSV, as well as the header for new files.\"\"\"\n conf_dict = dict(conf._asdict())\n # We need to check if the file exists before creating it.\n write_header = not tf.io.gfile.exists(path)\n with tf.io.gfile.GFile(path, 'a') as f:\n csv_writer = csv.DictWriter(f, fieldnames=conf_dict.keys())\n if write_header:\n csv_writer.writeheader()\n csv_writer.writerow(conf_dict)\n\n\ndef fetch_anndata(path, from_gcs):\n \"\"\"Reads the input data and turns it into an anndata.AnnData object.\"\"\"\n _, ext = os.path.splitext(path)\n\n # AnnData is based of HDF5 and doesn't have GCS file handlers\n # so we have to locally copy the file before reading it.\n if from_gcs:\n with tempfile.NamedTemporaryFile(delete=False) as tmp_file:\n tmp_path = tmp_file.name\n tf.io.gfile.copy(path, tmp_path, overwrite=True)\n path = tmp_path\n\n if ext == '.h5ad':\n adata = anndata.read_h5ad(path)\n elif ext == '.loom':\n adata = anndata.read_loom(path)\n else:\n raise app.UsageError('Only supports loom and h5ad files.')\n\n return adata\n\n\ndef write_anndata(save_h5ad, adata, log_folder, conf, tissue, n_layers,\n n_hidden, dispersion, dropout_rate, reconstruction_loss):\n \"\"\"Writes anndata object with the proper name on GCS and returns the name.\"\"\"\n # We need to write the anndata locally and copy it to GCS for the same\n # reason as before.\n if not save_h5ad:\n return ''\n\n with tempfile.NamedTemporaryFile(suffix='.h5ad', delete=True) as tmp_file:\n adata.write(tmp_file.name)\n h5ad_fname = os.path.join(\n log_folder, f'{tissue}.method=scvi.seed={conf.seed}.'\n f'n_latent={conf.n_latent}.n_layers={n_layers}.n_hidden={n_hidden}.'\n f'dispersion={dispersion}.dropout_rate={dropout_rate}.'\n f'reconstruction_loss={reconstruction_loss}.epochs={conf.epochs}.'\n f'lr={conf.lr}.h5ad')\n tf.io.gfile.copy(tmp_file.name, h5ad_fname, overwrite=True)\n return h5ad_fname\n\n\ndef generate_conf(n_latent, epochs, lr, seed):\n \"\"\"Generates the local parameter grid.\"\"\"\n local_param_grid = {\n 'n_latent': [2, 8, 10, 16, 32, 50, 64, 128]\n if n_latent is None else [n_latent],\n 'epochs': [20, 50, 100, 200, 300, 500, 1000]\n if epochs is None else [epochs],\n 'lr': [1e-2, 1e-3, 1e-4] if lr is None else [lr],\n 'seed': [0, 1, 2, 3, 4] if seed is None else [seed]\n }\n\n return [Conf(*vals) for vals in itertools.product(*local_param_grid.values())]\n\n\ndef fetch_previous_runs(log_path):\n \"\"\"Reads in the state in which the previous run stopped.\"\"\"\n previous_runs = set()\n if tf.io.gfile.exists(log_path):\n with tf.io.gfile.GFile(log_path, mode='r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n # Note: we need to do this conversion because DictReader creates an\n # OrderedDict, and reads all values as str instead of bool or int.\n previous_runs.add(\n str(\n Conf(\n n_latent=int(row['n_latent']),\n epochs=int(row['epochs']),\n lr=float(row['lr']),\n seed=int(row['seed']),\n )))\n\n logging.info('Previous runs:')\n for run in previous_runs:\n logging.info(run)\n\n return previous_runs\n\n\ndef main(unused_argv):\n tissue, _ = os.path.splitext(os.path.basename(FLAGS.input_path))\n adata = fetch_anndata(FLAGS.input_path, FLAGS.from_gcs)\n sc.pp.filter_genes(adata, min_cells=1)\n scvi_dataset = scvi.dataset.AnnDatasetFromAnnData(adata)\n\n n_clusters = adata.obs['label'].nunique()\n\n confs = generate_conf(\n n_latent=FLAGS.n_latent,\n epochs=FLAGS.epochs,\n lr=FLAGS.lr,\n seed=FLAGS.seed)\n total_runs = len(confs)\n previous_runs = fetch_previous_runs(FLAGS.log_path)\n\n for i, conf in enumerate(confs):\n if str(conf) in previous_runs:\n logging.info('Skipped %s', conf)\n continue\n\n np.random.seed(conf.seed)\n random.seed(conf.seed)\n torch.manual_seed(conf.seed)\n latent, elbo_train_set, elbo_test_set = compute_scvi_latent(\n scvi_dataset=scvi_dataset,\n n_latent=conf.n_latent,\n n_layers=FLAGS.n_layers,\n n_hidden=FLAGS.n_hidden,\n dropout_rate=FLAGS.dropout_rate,\n dispersion=FLAGS.dispersion,\n n_epochs=conf.epochs,\n lr=conf.lr,\n reconstruction_loss=FLAGS.reconstruction_loss,\n )\n adata.obsm['X_scvi'] = latent\n metrics = evaluate_method(adata, n_clusters)\n\n log_folder = os.path.dirname(FLAGS.output_csv)\n\n h5ad_fname = write_anndata(\n adata=adata,\n save_h5ad=FLAGS.save_h5ad,\n log_folder=log_folder,\n conf=conf,\n tissue=tissue,\n n_layers=FLAGS.n_layers,\n n_hidden=FLAGS.n_hidden,\n dispersion=FLAGS.dispersion,\n dropout_rate=FLAGS.dropout_rate,\n reconstruction_loss=FLAGS.reconstruction_loss)\n\n run_result = RunResult(\n method='scvi',\n seed=conf.seed,\n n_latent=conf.n_latent,\n n_layers=FLAGS.n_layers,\n n_hidden=FLAGS.n_hidden,\n dispersion=FLAGS.dispersion,\n dropout_rate=FLAGS.dropout_rate,\n reconstruction_loss=FLAGS.reconstruction_loss,\n epochs=conf.epochs,\n lr=conf.lr,\n silhouette=metrics.silhouette,\n kmeans_silhouette=metrics.kmeans_silhouette,\n kmeans_ami=metrics.ami,\n kmeans_ari=metrics.ari,\n n_cells=adata.n_obs,\n tissue=tissue,\n n_clusters=n_clusters,\n elbo_train_set=elbo_train_set[-1],\n elbo_test_set=elbo_test_set[-1],\n h5ad_fname=h5ad_fname)\n log_run(FLAGS.output_csv, run_result)\n\n logging.info(conf)\n logging.info('Done with %s out of %s', i, total_runs)\n log_run(FLAGS.log_path, conf)\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('input_path')\n flags.mark_flag_as_required('output_csv')\n flags.mark_flag_as_required('log_path')\n flags.mark_flag_as_required('n_layers')\n flags.mark_flag_as_required('n_hidden')\n flags.mark_flag_as_required('dispersion')\n flags.mark_flag_as_required('dropout_rate')\n flags.mark_flag_as_required('reconstruction_loss')\n app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utilities for CNN benchmarks.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport threading\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\n\ndef tensorflow_version_tuple():\n v = tf.__version__\n major, minor, patch = v.split('.')\n return (int(major), int(minor), patch)\n\n\ndef tensorflow_version():\n vt = tensorflow_version_tuple()\n return vt[0] * 1000 + vt[1]\n\n\ndef log_fn(log):\n print(log)\n\n\ndef roll_numpy_batches(array, batch_size, shift_ratio):\n \"\"\"Moves a proportion of batches from start to the end of the array.\n\n This function moves a proportion of batches, specified by `shift_ratio`, from\n the starts of the array to the end. The number of batches moved is rounded\n down to the nearest integer. For example,\n\n ```\n roll_numpy_batches([1, 2, 3, 4, 5, 6], 2, 0.34) == [3, 4, 5, 6, 1, 2]\n ```\n\n Args:\n array: A Numpy array whose first dimension is the batch dimension.\n batch_size: The batch size.\n shift_ratio: Proportion of batches to move from the start of the array to\n the end of the array.\n Returns:\n A new Numpy array, with a proportion of the batches at the start of `array`\n moved to the end.\n \"\"\"\n num_items = array.shape[0]\n assert num_items % batch_size == 0\n num_batches = num_items // batch_size\n starting_batch = int(num_batches * shift_ratio)\n starting_item = starting_batch * batch_size\n return np.roll(array, -starting_item, axis=0)\n\n\n# For Python 2.7 compatibility, we do not use threading.Barrier.\nclass Barrier(object):\n \"\"\"Implements a lightweight Barrier.\n\n Useful for synchronizing a fixed number of threads at known synchronization\n points. Threads block on 'wait()' and simultaneously return once they have\n all made that call.\n\n # Implementation adopted from boost/thread/barrier.hpp\n \"\"\"\n\n def __init__(self, parties):\n \"\"\"Create a barrier, initialised to 'parties' threads.\"\"\"\n self.cond = threading.Condition(threading.Lock())\n self.parties = parties\n # Indicates the number of waiting parties.\n self.waiting = 0\n # generation is needed to deal with spurious wakeups. If self.cond.wait()\n # wakes up for other reasons, generation will force it go back to wait().\n self.generation = 0\n self.broken = False\n\n def wait(self):\n \"\"\"Wait for the barrier.\"\"\"\n with self.cond:\n # Check if the barrier has been disabled or not.\n if self.broken:\n return\n gen = self.generation\n self.waiting += 1\n if self.waiting == self.parties:\n self.waiting = 0\n self.generation += 1\n self.cond.notify_all()\n # loop because of spurious wakeups\n while gen == self.generation:\n self.cond.wait()\n\n # TODO(huangyp): Remove this method once we find a way to know which step\n # is the last barrier.\n def abort(self):\n \"\"\"Clear existing barrier and disable this barrier.\"\"\"\n with self.cond:\n if self.waiting > 0:\n self.generation += 1\n self.cond.notify_all()\n self.broken = True\n\n\nclass ImageProducer(object):\n \"\"\"An image producer that puts images into a staging area periodically.\n\n This class is useful for periodically running a set of ops, `put_ops` on a\n different thread every `batch_group_size` steps.\n\n The notify_image_consumption() method is used to increment an internal counter\n so that every `batch_group_size` times it is called, `put_ops` is executed. A\n barrier is placed so that notify_image_consumption() will block until\n the previous call to `put_ops` has been executed.\n\n The start() method is used to start the thread that runs `put_ops`.\n\n The done() method waits until the last put_ops is executed and stops the\n thread.\n\n The purpose of this class is to fill an image input pipeline every\n `batch_group_size` steps. Suppose `put_ops` supplies `batch_group_size` images\n to the input pipeline when run, and that every step, 1 batch of images is\n consumed. Then, by calling notify_image_consumption() every step, images are\n supplied to the input pipeline at the same amount they are consumed.\n\n Example usage:\n ```\n put_ops = ... # Enqueues `batch_group_size` batches to a StagingArea\n get_op = ... # Dequeues 1 batch, and does some operations on it\n batch_group_size = 4\n with tf.Session() as sess:\n image_producer = cnn_util.ImageProducer(sess, put_op, batch_group_size)\n image_producer.start()\n for _ in range(100):\n sess.run(get_op)\n image_producer.notify_image_consumption()\n ```\n \"\"\"\n\n def __init__(self, sess, put_ops, batch_group_size, use_python32_barrier):\n self.sess = sess\n self.num_gets = 0\n self.put_ops = put_ops\n self.batch_group_size = batch_group_size\n self.done_event = threading.Event()\n if (use_python32_barrier and\n sys.version_info[0] == 3 and sys.version_info[1] >= 2):\n self.put_barrier = threading.Barrier(2)\n else:\n self.put_barrier = Barrier(2)\n\n def _should_put(self):\n return (self.num_gets + 1) % self.batch_group_size == 0\n\n def done(self):\n \"\"\"Stop the image producer.\"\"\"\n self.done_event.set()\n self.put_barrier.abort()\n self.thread.join()\n\n def start(self):\n \"\"\"Start the image producer.\"\"\"\n self.sess.run([self.put_ops])\n self.thread = threading.Thread(target=self._loop_producer)\n # Set daemon to true to allow Ctrl + C to terminate all threads.\n self.thread.daemon = True\n self.thread.start()\n\n def notify_image_consumption(self):\n \"\"\"Increment the counter of image_producer by 1.\n\n This should only be called by the main thread that consumes images and runs\n the model computation. One batch of images should be consumed between\n calling start() and the first call to this method. Then, one batch of images\n should be consumed between any two successive calls to this method.\n \"\"\"\n if self._should_put():\n self.put_barrier.wait()\n self.num_gets += 1\n\n def _loop_producer(self):\n while not self.done_event.isSet():\n self.sess.run([self.put_ops])\n self.put_barrier.wait()\n\n\nclass BaseClusterManager(object):\n \"\"\"The manager for the cluster of servers running the benchmark.\"\"\"\n\n def __init__(self, params):\n worker_hosts = params.worker_hosts.split(',')\n ps_hosts = params.ps_hosts.split(',') if params.ps_hosts else []\n cluster = {'worker': worker_hosts}\n if ps_hosts:\n cluster['ps'] = ps_hosts\n self._cluster_spec = tf.train.ClusterSpec(cluster)\n\n def get_target(self):\n \"\"\"Returns a target to be passed to tf.Session().\"\"\"\n raise NotImplementedError('get_target must be implemented by subclass')\n\n def join_server(self):\n raise NotImplementedError('join must be implemented by subclass')\n\n def get_cluster_spec(self):\n return self._cluster_spec\n\n def num_workers(self):\n return len(self._cluster_spec.job_tasks('worker'))\n\n def num_ps(self):\n if 'ps' in self._cluster_spec.jobs:\n return len(self._cluster_spec.job_tasks('ps'))\n else:\n return 0\n\n\nclass GrpcClusterManager(BaseClusterManager):\n \"\"\"A cluster manager for a cluster networked with gRPC.\"\"\"\n\n def __init__(self, params, config_proto):\n super(GrpcClusterManager, self).__init__(params)\n if params.job_name == 'controller':\n self._target = 'grpc://%s' % self._cluster_spec.job_tasks('worker')[0]\n else:\n self._server = tf.train.Server(self._cluster_spec,\n job_name=params.job_name,\n task_index=params.task_index,\n config=config_proto,\n protocol=params.server_protocol)\n self._target = self._server.target\n\n def get_target(self):\n return self._target\n\n def join_server(self):\n return self._server.join()\n" ]
[ [ "tensorflow.compat.v1.ones_like", "tensorflow.compat.v1.stack", "tensorflow.compat.v1.image.flip_up_down", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.reduce_sum", "tensorflow.compat.v1.space_to_depth", "tensorflow.compat.v1.image.flip_left_right", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.maximum", "tensorflow.compat.v1.clip_by_value", "tensorflow.compat.v1.image.resize_bilinear", "tensorflow.compat.v1.name_scope" ], [ "tensorflow.convert_to_tensor", "tensorflow.constant", "tensorflow.zeros", "tensorflow.random.uniform", "tensorflow.test.main", "tensorflow.eye" ], [ "tensorflow.compat.v1.nn.dropout", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.math.reduce_sum", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.math.reduce_mean", "tensorflow.compat.v1.ones", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.einsum", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.transpose", "tensorflow.compat.v1.split", "tensorflow.compat.v1.fill", "tensorflow.compat.v1.nn.relu", "tensorflow.compat.v1.math.reduce_max", "tensorflow.compat.v1.math.cumsum", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.slice", "tensorflow.compat.v1.repeat", "tensorflow.compat.v1.squeeze", "tensorflow.compat.v1.pad" ], [ "tensorflow.compat.v1.not_equal", "tensorflow.compat.v1.reduce_all", "numpy.sqrt", "tensorflow.compat.v1.equal", "tensorflow.compat.v1.zeros_initializer", "tensorflow.compat.v1.train.Scaffold", "tensorflow.compat.v1.tpu.CrossShardOptimizer", "tensorflow.compat.v1.train.AdamOptimizer", "tensorflow.compat.v1.multiply", "tensorflow.compat.v1.trainable_variables", "tensorflow.compat.v1.train.get_or_create_global_step", "tensorflow.compat.v1.layers.flatten", "tensorflow.contrib.tpu.cross_replica_sum", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.keras.backend.std", "tensorflow.compat.v1.init_from_checkpoint", "tensorflow.compat.v1.estimator.tpu.TPUEstimatorSpec", "tensorflow.compat.v1.reduce_max", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.estimator.export.PredictOutput", "tensorflow.compat.v1.train.get_global_step", "tensorflow.compat.v1.reduce_min", "tensorflow.compat.v1.clip_by_global_norm" ], [ "tensorflow.compat.v2.sysconfig.get_link_flags", "tensorflow.compat.v2.sysconfig.get_compile_flags" ], [ "matplotlib.pyplot.legend", "matplotlib.pyplot.imshow", "numpy.linspace", "matplotlib.pyplot.scatter", "matplotlib.use", "matplotlib.pyplot.ylim", "matplotlib.pyplot.savefig", "numpy.max", "matplotlib.pyplot.xlim", "matplotlib.pyplot.close", "matplotlib.pyplot.axis", "numpy.meshgrid", "matplotlib.pyplot.figure" ], [ "torch.nn.utils.rnn.PackedSequence", "torch.LongTensor", "torch.nn.LSTM", "torch.cat" ], [ "tensorflow.compat.v2.rank", "tensorflow.compat.v2.minimum", "tensorflow.compat.v2.shape", "tensorflow.compat.v2.convert_to_tensor", "tensorflow.compat.v2.ones", "tensorflow.compat.v2.reduce_max", "tensorflow.compat.v2.reduce_sum", "tensorflow.compat.v2.data.Dataset.from_tensor_slices", "tensorflow.compat.v2.norm", "tensorflow.compat.v2.name_scope", "tensorflow.compat.v2.io.gfile.makedirs", "tensorflow.compat.v2.reshape", "tensorflow.compat.v2.stack", "tensorflow.compat.v2.zeros", "tensorflow.compat.v2.train.Checkpoint", "tensorflow.compat.v2.Variable", "tensorflow.compat.v2.function", "numpy.log", "tensorflow.compat.v2.reduce_min", "tensorflow.compat.v2.square", "tensorflow.compat.v2.reduce_mean", "tensorflow.compat.v2.zeros_like", "tensorflow.compat.v2.random.normal", "tensorflow.compat.v2.GradientTape", "tensorflow.compat.v2.io.gfile.exists", "tensorflow.compat.v2.cast", "numpy.prod" ], [ "tensorflow.compat.v1.train.polynomial_decay", "tensorflow.compat.v1.square", "tensorflow.compat.v1.multiply", "tensorflow.compat.v1.trainable_variables", "tensorflow.compat.v1.sqrt", "tensorflow.compat.v1.zeros_initializer", "tensorflow.compat.v1.train.get_or_create_global_step", "tensorflow.compat.v1.gradients", "tensorflow.compat.v1.group", "tensorflow.compat.v1.maximum", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.math.rsqrt", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.clip_by_global_norm", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.tpu.CrossShardOptimizer" ], [ "numpy.argsort", "numpy.frombuffer", "tensorflow.sparse.to_dense", "numpy.mean" ], [ "numpy.array", "numpy.random.RandomState" ], [ "tensorflow.compat.v1.equal", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.reduce_sum", "tensorflow.compat.v1.zeros", "numpy.ones", "tensorflow.compat.v1.to_float", "tensorflow.python.ops.array_ops.reshape", "tensorflow.compat.v1.to_int64", "tensorflow.compat.v1.zeros_like", "tensorflow.compat.v1.diag_part", "tensorflow.python.ops.math_ops.cast", "tensorflow.compat.v1.variable_scope", "numpy.zeros", "tensorflow.compat.v1.where" ], [ "tensorflow.compat.v2.exp", "tensorflow.compat.v2.norm", "tensorflow.compat.v2.keras.metrics.Mean", "tensorflow.compat.v2.equal", "tensorflow.compat.v2.reduce_sum", "tensorflow.compat.v2.GradientTape", "tensorflow.compat.v2.concat", "tensorflow.compat.v2.reduce_mean", "tensorflow.compat.v2.keras.layers.Dense", "tensorflow.compat.v2.keras.optimizers.Adam", "numpy.finfo", "tensorflow.compat.v2.ones", "tensorflow.compat.v2.reduce_max", "tensorflow.compat.v2.math.log", "tensorflow.compat.v2.random.uniform" ], [ "tensorflow.io.gfile.listdir", "tensorflow.test.main" ], [ "tensorflow.compat.v2.data.Dataset.from_tensor_slices", "tensorflow.compat.v2.io.gfile.remove", "tensorflow.compat.v2.io.gfile.makedirs", "numpy.ones", "numpy.testing.assert_array_equal", "tensorflow.compat.v2.io.gfile.join", "numpy.testing.assert_raises", "tensorflow.compat.v2.constant", "tensorflow.compat.v2.io.gfile.walk" ], [ "tensorflow.zeros", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.rank", "tensorflow.stop_gradient", "tensorflow.gather", "numpy.zeros", "tensorflow.matmul", "tensorflow.math.cos", "tensorflow.random.truncated_normal", "tensorflow.shape", "tensorflow.random.uniform", "tensorflow.one_hot", "numpy.sum", "tensorflow.GradientTape", "tensorflow.nest.map_structure", "tensorflow.math.sqrt", "tensorflow.reduce_mean", "tensorflow.maximum", "tensorflow.ones", "tensorflow.math.log", "tensorflow.keras.optimizers.Adam", "tensorflow.random.normal", "tensorflow.abs" ], [ "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.keras.models.Sequential", "tensorflow.compat.v1.contrib.summary.scalar", "tensorflow.compat.v1.zeros", "tensorflow.compat.v1.keras.layers.Dense", "tensorflow.compat.v1.constant" ], [ "torch.zeros", "torch.nn.Embedding", "torch.repeat_interleave", "torch.where", "torch.nn.Dropout", "torch.softmax", "torch.ones", "torch.einsum", "torch.eye", "torch.relu", "torch.bmm", "torch.arange", "torch.ones_like", "torch.nn.functional.pad", "torch.sigmoid", "torch.nn.Linear", "torch.stack", "torch.nn.LayerNorm", "torch.nn.Tanh" ], [ "tensorflow.convert_to_tensor", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.while_loop", "tensorflow.concat", "tensorflow.shape", "tensorflow.TensorArray", "tensorflow.zeros", "tensorflow.reshape", "tensorflow.random.uniform", "tensorflow.keras.initializers.GlorotUniform", "tensorflow.tile" ], [ "numpy.array", "numpy.zeros" ], [ "numpy.dot", "numpy.expand_dims", "numpy.sqrt", "tensorflow.reduce_sum", "numpy.flipud", "numpy.max", "numpy.mean", "numpy.random.randn", "numpy.exp", "numpy.random.randint", "numpy.square", "numpy.linalg.svd", "numpy.clip", "numpy.fliplr", "numpy.arange", "numpy.eye", "numpy.stack", "numpy.sin", "numpy.copy", "tensorflow.square", "numpy.zeros", "tensorflow.matmul", "numpy.nonzero", "numpy.linalg.inv", "numpy.delete", "numpy.transpose", "numpy.meshgrid", "numpy.array", "tensorflow.transpose", "numpy.cos", "numpy.ones", "matplotlib.cm.get_cmap", "numpy.random.uniform", "tensorflow.sqrt" ], [ "tensorflow.compat.v2.strings.unicode_split", "tensorflow.compat.v2.concat", "tensorflow.compat.v2.data.TFRecordDataset", "tensorflow.compat.v2.strings.split", "tensorflow.compat.v2.io.FixedLenFeature" ], [ "matplotlib.pyplot.imsave", "tensorflow.compat.v2.data.Dataset.from_tensor_slices", "tensorflow.compat.v2.io.gfile.GFile", "tensorflow.compat.v2.io.gfile.makedirs", "tensorflow.compat.v2.image.rgb_to_grayscale", "tensorflow.compat.v2.convert_to_tensor", "numpy.ceil", "tensorflow.compat.v2.zeros", "tensorflow.compat.v2.io.gfile.listdir", "tensorflow.compat.v2.image.decode_image", "tensorflow.compat.v2.io.read_file" ], [ "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.nn.sigmoid", "tensorflow.one_hot", "tensorflow.random.normal", "tensorflow.GradientTape" ], [ "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.flags.DEFINE_string", "tensorflow.compat.v1.tile", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.disable_eager_execution", "tensorflow.compat.v1.train.init_from_checkpoint", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.app.run" ], [ "tensorflow.convert_to_tensor", "tensorflow.nn.softmax_cross_entropy_with_logits", "numpy.round", "tensorflow.pad", "numpy.pad", "numpy.float32", "numpy.zeros", "tensorflow.keras.metrics.Mean", "tensorflow.nn.convolution", "tensorflow.keras.Model", "numpy.array", "tensorflow.GradientTape", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.transpose", "tensorflow.reduce_mean", "tensorflow.repeat", "tensorflow.keras.optimizers.Adam", "numpy.prod" ], [ "tensorflow.compat.v1.not_equal", "tensorflow.compat.v1.random.uniform", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.equal", "tensorflow.compat.v1.case", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.switch_case", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.identity", "tensorflow.compat.v1.cumsum", "tensorflow.compat.v1.where_v2", "tensorflow.compat.v1.nn.depthwise_conv2d", "tensorflow.compat.v1.ones", "tensorflow.compat.v1.bitwise.right_shift", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.reduce_sum", "tensorflow.compat.v1.maximum", "tensorflow.compat.v1.image.convert_image_dtype", "tensorflow.compat.v1.zeros_like", "tensorflow.compat.v1.ones_like", "tensorflow.compat.v1.less", "tensorflow.compat.v1.zeros", "tensorflow.compat.v1.tile", "tensorflow.compat.v1.clip_by_value", "tensorflow.compat.v1.cond", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.reduce_max", "tensorflow.compat.v1.image.rgb_to_grayscale", "tensorflow.compat.v1.stack", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.histogram_fixed_width", "tensorflow.compat.v1.convert_to_tensor", "tensorflow.compat.v1.gather", "tensorflow.compat.v1.slice", "tensorflow.compat.v1.reduce_min", "tensorflow.compat.v1.pad" ], [ "tensorflow.constant" ], [ "numpy.random.seed", "numpy.unique", "tensorflow.io.gfile.exists", "tensorflow.io.gfile.GFile", "numpy.isnan", "torch.manual_seed", "tensorflow.io.gfile.copy" ], [ "tensorflow.compat.v1.train.Server", "numpy.roll", "tensorflow.compat.v1.train.ClusterSpec" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "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": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.4", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
manuelmusngi/machine_learning_algorithms_for_development
[ "f344634f84d8f3a60fbb93892bdaed877855b710", "f344634f84d8f3a60fbb93892bdaed877855b710", "f344634f84d8f3a60fbb93892bdaed877855b710" ]
[ "preprocessing_tools.py", "k_fold_cross_validation.py", "k_nearest_neighbors.py" ]
[ "# Data Preprocessing Tools for Data Cleaning\n\n# Import libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_ ('')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\nprint(X)\nprint(y)\n\n# Taking care of missing data\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer(missing_values=np.nan, strategy='mean')\nimputer.fit(X[:, 1:3])\nX[:, 1:3] = imputer.transform(X[:, 1:3])\nprint(X)\n\n# Encoding categorical data\n\n# Encoding the Independent Variable\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\nct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0])], remainder='passthrough')\nX = np.array(ct.fit_transform(X))\nprint(X)\n\n# Encoding the Dependent Variable\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ny = le.fit_transform(y)\nprint(y)\n\n# Splitting the dataset into the Training set and Test set\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 = 1)\nprint(X_train)\nprint(X_test)\nprint(y_train)\nprint(y_test)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train[:, 3:] = sc.fit_transform(X_train[:, 3:])\nX_test[:, 3:] = sc.transform(X_test[:, 3:])\nprint(X_train)\nprint(X_test)\n", "# k-Fold Cross Validation\n\n# Import libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Import dataset\ndataset = pd.read_ ('')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\n\n# Split dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n# Training the Kernel SVM model on the Training set\nfrom sklearn.svm import SVC\nclassifier = SVC(kernel = 'rbf', random_state = 0)\nclassifier.fit(X_train, y_train)\n\n# Confusion Matrix - classification model performance\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ny_pred = classifier.predict(X_test)\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)\n\n# Apply k-Fold Cross Validation\nfrom sklearn.model_selection import cross_val_score\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)\nprint(\"Accuracy: {:.2f} %\".format(accuracies.mean()*100))\nprint(\"Standard Deviation: {:.2f} %\".format(accuracies.std()*100))\n\n# Visualize the Training set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_train, y_train\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Kernel SVM (Training set)')\nplt.xlabel('Age')\nplt.ylabel('Estimated Salary')\nplt.legend()\nplt.show()\n\n# Visualize Test set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Kernel SVM (Test set)')\nplt.xlabel('')\nplt.ylabel('')\nplt.legend()\nplt.show()\n", "# K-Nearest Neighbors (K-NN)\n\n# Import libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Import the dataset\ndataset = pd.read_ ('')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\nprint(X_train)\nprint(y_train)\nprint(X_test)\nprint(y_test)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\nprint(X_train)\nprint(X_test)\n\n# Train the K-NN model on the Training set\nfrom sklearn.neighbors import KNeighborsClassifier\nclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)\nclassifier.fit(X_train, y_train)\n\n# Predict training set result\nprint(classifier.predict(sc.transform([[30,87000]])))\n\n# Predict test set results\ny_pred = classifier.predict(X_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\n\n# Confusion Matrix performance\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)\n\n# Visualize Training set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = sc.inverse_transform(X_train), y_train\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 1),\n np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 1))\nplt.contourf(X1, X2, classifier.predict(sc.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('')\nplt.xlabel('')\nplt.ylabel('')\nplt.legend()\nplt.show()\n\n# Visualize Test set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = sc.inverse_transform(X_test), y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 1),\n np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 1))\nplt.contourf(X1, X2, classifier.predict(sc.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('')\nplt.xlabel('')\nplt.ylabel('')\nplt.legend()\nplt.show()\n" ]
[ [ "pandas.read_", "sklearn.preprocessing.OneHotEncoder", "sklearn.impute.SimpleImputer", "sklearn.model_selection.train_test_split", "sklearn.preprocessing.StandardScaler", "sklearn.preprocessing.LabelEncoder" ], [ "matplotlib.pyplot.legend", "pandas.read_", "sklearn.model_selection.cross_val_score", "matplotlib.pyplot.title", "numpy.unique", "sklearn.metrics.confusion_matrix", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.ylabel", "matplotlib.colors.ListedColormap", "sklearn.svm.SVC", "matplotlib.pyplot.xlabel", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.show", "sklearn.metrics.accuracy_score" ], [ "matplotlib.pyplot.legend", "pandas.read_", "matplotlib.pyplot.title", "numpy.unique", "sklearn.metrics.confusion_matrix", "sklearn.model_selection.train_test_split", "sklearn.neighbors.KNeighborsClassifier", "matplotlib.pyplot.ylabel", "matplotlib.colors.ListedColormap", "matplotlib.pyplot.xlabel", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.show", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qianrusun1015/Disentangled-Person-Image-Generation
[ "e4703860bb1b351050ce50f339985ff0811f1d64" ]
[ "score_mask.py" ]
[ "from __future__ import print_function\n\nimport os, pdb, sys, glob\n# we need to set GPUno first, otherwise may out of memory\nstage = int(sys.argv[1])\ngpuNO = sys.argv[2]\nmodel_dir = sys.argv[3]\ntest_dir = sys.argv[4]\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=str(gpuNO)\nimport StringIO\nimport scipy.misc\nimport numpy as np\nfrom skimage.measure import compare_ssim as ssim\nfrom skimage.measure import compare_psnr as psnr\nfrom skimage.color import rgb2gray\n# from PIL import Image\nimport scipy.misc\nimport tflib\nimport tflib.inception_score\n\ndef l1_mean_dist(x,y): \n # return np.sum(np.abs(x-y))\n diff = x.astype(float)-y.astype(float)\n return np.sum(np.abs(diff))/np.product(x.shape)\n\ndef l2_mean_dist(x,y): \n # return np.sqrt(np.sum((x-y)**2))\n diff = x.astype(float)-y.astype(float)\n return np.sqrt(np.sum(diff**2))/np.product(x.shape)\n\n# pdb.set_trace()\n\nif 1==stage:\n test_result_dir_x = os.path.join(model_dir, test_dir, 'x_target')\n # test_result_dir_x = os.path.join(model_dir, test_dir, 'x')\n test_result_dir_G = os.path.join(model_dir, test_dir, 'G')\n test_result_dir_mask = os.path.join(model_dir, test_dir, 'mask')\n score_path = os.path.join(model_dir, test_dir, 'score_mask.txt')\n\n types = ('*.jpg', '*.png') # the tuple of file types\n x_files = []\n G_files = []\n mask_files = []\n for files in types:\n x_files.extend(glob.glob(os.path.join(test_result_dir_x, files)))\n G_files.extend(glob.glob(os.path.join(test_result_dir_G, files)))\n mask_files.extend(glob.glob(os.path.join(test_result_dir_mask, files)))\n x_target_list = []\n for path in x_files:\n x_target_list.append(scipy.misc.imread(path))\n G_list = []\n for path in G_files:\n G_list.append(scipy.misc.imread(path))\n mask_target_list = []\n for path in mask_files:\n mask_target_list.append(scipy.misc.imread(path))\n N = len(G_files)\n \n ##################### SSIM ##################\n ssim_G_x = []\n psnr_G_x = []\n L1_mean_G_x = []\n L2_mean_G_x = []\n # x_0_255 = utils_wgan.unprocess_image(x_fixed, 127.5, 127.5)\n x_0_255 = x_target_list\n for i in xrange(N):\n # G_gray = rgb2gray((G_list[i]/127.5-1).clip(min=-1,max=1))\n # x_target_gray = rgb2gray((x_target_list[i]/127.5-1).clip(min=-1,max=1))\n # gray image, [0,1]\n # G_gray = rgb2gray((G_list[i]).clip(min=0,max=255))\n # x_target_gray = rgb2gray((x_target_list[i]).clip(min=0,max=255))\n # ssim_G_x.append(ssim(G_gray, x_target_gray, data_range=x_target_gray.max()-x_target_gray.min(), multichannel=False))\n # psnr_G_x.append(psnr(im_true=x_target_gray, im_test=G_gray, data_range=x_target_gray.max()-x_target_gray.min())) \n # L1_mean_G_x.append(l1_mean_dist(G_gray, x_target_gray))\n # L2_mean_G_x.append(l2_mean_dist(G_gray, x_target_gray))\n \n # color image\n # ssim_G_x.append(ssim(G_list[i], x_target_list[i], multichannel=True))\n masked_G_array = np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*G_list[i])\n masked_x_target_array = np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*x_target_list[i])\n ssim_G_x.append(ssim(masked_G_array, masked_x_target_array, multichannel=True))\n \n psnr_G_x.append(psnr(im_true=masked_x_target_array, im_test=masked_G_array))\n L1_mean_G_x.append(l1_mean_dist(masked_G_array, masked_x_target_array))\n L2_mean_G_x.append(l2_mean_dist(masked_G_array, masked_x_target_array))\n # pdb.set_trace()\n ssim_G_x_mean = np.mean(ssim_G_x)\n ssim_G_x_std = np.std(ssim_G_x)\n psnr_G_x_mean = np.mean(psnr_G_x)\n psnr_G_x_std = np.std(psnr_G_x)\n L1_G_x_mean = np.mean(L1_mean_G_x)\n L1_G_x_std = np.std(L1_mean_G_x)\n L2_G_x_mean = np.mean(L2_mean_G_x)\n L2_G_x_std = np.std(L2_mean_G_x)\n print('ssim_G_x_mean: %f\\n' % ssim_G_x_mean)\n print('ssim_G_x_std: %f\\n' % ssim_G_x_std)\n print('psnr_G_x_mean: %f\\n' % psnr_G_x_mean)\n print('psnr_G_x_std: %f\\n' % psnr_G_x_std)\n print('L1_G_x_mean: %f\\n' % L1_G_x_mean)\n print('L1_G_x_std: %f\\n' % L1_G_x_std)\n print('L2_G_x_mean: %f\\n' % L2_G_x_mean)\n print('L2_G_x_std: %f\\n' % L2_G_x_std)\n\n # ##################### Inception score ##################\n # # IS_G_mean, IS_G_std = tflib.inception_score.get_inception_score(G_list)\n # G_list_masked = [np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*G_list[i]) for i in range(len(G_list))]\n # IS_G_mean, IS_G_std = tflib.inception_score.get_inception_score(G_list_masked)\n # print('IS_G_mean: %f\\n' % IS_G_mean)\n # print('IS_G_std: %f\\n' % IS_G_std)\n\n # with open(score_path, 'w') as f:\n # f.write('Image number: %d\\n' % N)\n # f.write('ssim: %.5f +- %.5f ' % (ssim_G_x_mean, ssim_G_x_std))\n # f.write('IS: %.5f +- %.5f ' % (IS_G_mean, IS_G_std))\n # f.write('psnr: %.5f +- %.5f ' % (psnr_G_x_mean, psnr_G_x_std))\n # f.write('L1: %.5f +- %.5f ' % (L1_G_x_mean, L1_G_x_std))\n # f.write('L2: %.5f +- %.5f' % (L2_G_x_mean, L2_G_x_std))\n\n ## IS of fake data\n G_list_masked = [np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*G_list[i]) for i in range(len(G_list))]\n IS_G_mean, IS_G_std = tflib.inception_score.get_inception_score(G_list_masked)\n print('IS_G_mean: %f\\n' % IS_G_mean)\n print('IS_G_std: %f\\n' % IS_G_std)\n with open(score_path, 'w') as f:\n f.write('Image number: %d\\n' % N)\n f.write('IS: %.5f +- %.5f ' % (IS_G_mean, IS_G_std))\n\n ## IS of real data\n # x_target_list_masked = [np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*x_target_list[i]) for i in range(len(x_target_list))]\n # IS_G_mean, IS_G_std = tflib.inception_score.get_inception_score(x_target_list_masked)\n # print('IS_G_mean: %f\\n' % IS_G_mean)\n # print('IS_G_std: %f\\n' % IS_G_std)\n # with open(score_path+'_x_target', 'w') as f:\n # f.write('Image number: %d\\n' % N)\n # f.write('IS: %.5f +- %.5f ' % (IS_G_mean, IS_G_std))\n \nelif 2==stage:\n test_result_dir_x = os.path.join(model_dir, test_dir, 'x_target')\n test_result_dir_G1 = os.path.join(model_dir, test_dir, 'G1')\n test_result_dir_G2 = os.path.join(model_dir, test_dir, 'G2')\n test_result_dir_mask = os.path.join(model_dir, test_dir, 'mask')\n score_path = os.path.join(model_dir, test_dir, 'score_mask.txt') #\n\n types = ('*.jpg', '*.png') # the tuple of file types\n x_files = []\n G1_files = []\n G2_files = []\n mask_files = []\n for files in types:\n x_files.extend(glob.glob(os.path.join(test_result_dir_x, files)))\n G1_files.extend(glob.glob(os.path.join(test_result_dir_G1, files)))\n G2_files.extend(glob.glob(os.path.join(test_result_dir_G2, files)))\n mask_files.extend(glob.glob(os.path.join(test_result_dir_mask, files))) \n x_target_list = []\n for path in x_files:\n x_target_list.append(scipy.misc.imread(path))\n G1_list = []\n for path in G1_files:\n G1_list.append(scipy.misc.imread(path))\n G2_list = []\n for path in G2_files:\n G2_list.append(scipy.misc.imread(path))\n mask_target_list = []\n for path in mask_files:\n mask_target_list.append(scipy.misc.imread(path))\n\n ##################### SSIM G1 ##################\n N = len(x_files)\n ssim_G_x = []\n psnr_G_x = []\n L1_mean_G_x = []\n L2_mean_G_x = []\n # x_0_255 = utils_wgan.unprocess_image(x_fixed, 127.5, 127.5)\n # x_0_255 = x_target_list\n for i in xrange(N):\n # G1_gray = rgb2gray((G1_list[i]/127.5-1).clip(min=-1,max=1))\n # x_target_gray = rgb2gray((x_target_list[i]/127.5-1).clip(min=-1,max=1))\n # gray image, [0,1]\n # G1_gray = rgb2gray((G1_list[i]).clip(min=0,max=255))\n # x_target_gray = rgb2gray((x_target_list[i]).clip(min=0,max=255))\n # ssim_G_x.append(ssim(G_gray, x_target_gray, data_range=x_target_gray.max()-x_target_gray.min(), multichannel=False))\n # psnr_G_x.append(psnr(im_true=x_target_gray, im_test=G1_gray, data_range=x_target_gray.max()-x_target_gray.min())) \n # L1_mean_G_x.append(l1_mean_dist(G1_gray, x_target_gray))\n # L2_mean_G_x.append(l2_mean_dist(G1_gray, x_target_gray))\n \n # color image\n # ssim_G_x.append(ssim(G1_list[i], x_target_list[i], multichannel=True))\n masked_G1_array = np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*G1_list[i])\n masked_x_target_array = np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*x_target_list[i])\n ssim_G_x.append(ssim(masked_G1_array, masked_x_target_array, multichannel=True))\n \n psnr_G_x.append(psnr(im_true=masked_x_target_array, im_test=masked_G1_array))\n L1_mean_G_x.append(l1_mean_dist(masked_G1_array, masked_x_target_array))\n L2_mean_G_x.append(l2_mean_dist(masked_G1_array, masked_x_target_array))\n # pdb.set_trace()\n ssim_G1_x_mean = np.mean(ssim_G_x)\n ssim_G1_x_std = np.std(ssim_G_x)\n psnr_G1_x_mean = np.mean(psnr_G_x)\n psnr_G1_x_std = np.std(psnr_G_x)\n L1_G1_x_mean = np.mean(L1_mean_G_x)\n L1_G1_x_std = np.std(L1_mean_G_x)\n L2_G1_x_mean = np.mean(L2_mean_G_x)\n L2_G1_x_std = np.std(L2_mean_G_x)\n print('ssim_G1_x_mean: %f\\n' % ssim_G1_x_mean)\n print('ssim_G1_x_std: %f\\n' % ssim_G1_x_std)\n print('psnr_G1_x_mean: %f\\n' % psnr_G1_x_mean)\n print('psnr_G1_x_std: %f\\n' % psnr_G1_x_std)\n print('L1_G1_x_mean: %f\\n' % L1_G1_x_mean)\n print('L1_G1_x_std: %f\\n' % L1_G1_x_std)\n print('L2_G1_x_mean: %f\\n' % L2_G1_x_mean)\n print('L2_G1_x_std: %f\\n' % L2_G1_x_std)\n ##################### SSIM G2 ##################\n N = len(x_files)\n ssim_G_x = []\n psnr_G_x = []\n L1_mean_G_x = []\n L2_mean_G_x = []\n # x_0_255 = utils_wgan.unprocess_image(x_fixed, 127.5, 127.5)\n # x_0_255 = x_target_list\n for i in xrange(N):\n # G2_gray = rgb2gray((G2_list[i]/127.5-1).clip(min=-1,max=1))\n # x_target_gray = rgb2gray((x_target_list[i]/127.5-1).clip(min=-1,max=1))\n # gray image, [0,1]\n # G2_gray = rgb2gray((G2_list[i]).clip(min=0,max=255))\n # x_target_gray = rgb2gray((x_target_list[i]).clip(min=0,max=255))\n # ssim_G_x.append(ssim(G_gray, x_target_gray, data_range=x_target_gray.max()-x_target_gray.min(), multichannel=False))\n # psnr_G_x.append(psnr(im_true=x_target_gray, im_test=G2_gray, data_range=x_target_gray.max()-x_target_gray.min())) \n # L1_mean_G_x.append(l1_mean_dist(G2_gray, x_target_gray))\n # L2_mean_G_x.append(l2_mean_dist(G2_gray, x_target_gray))\n \n # color image\n # ssim_G_x.append(ssim(G2_list[i], x_target_list[i], multichannel=True))\n masked_G2_array = np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*G2_list[i])\n masked_x_target_array = np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*x_target_list[i])\n ssim_G_x.append(ssim(masked_G2_array, masked_x_target_array, multichannel=True))\n \n psnr_G_x.append(psnr(im_true=masked_x_target_array, im_test=masked_G2_array))\n L1_mean_G_x.append(l1_mean_dist(masked_G2_array, masked_x_target_array))\n L2_mean_G_x.append(l2_mean_dist(masked_G2_array, masked_x_target_array))\n # pdb.set_trace()\n ssim_G2_x_mean = np.mean(ssim_G_x)\n ssim_G2_x_std = np.std(ssim_G_x)\n psnr_G2_x_mean = np.mean(psnr_G_x)\n psnr_G2_x_std = np.std(psnr_G_x)\n L1_G2_x_mean = np.mean(L1_mean_G_x)\n L1_G2_x_std = np.std(L1_mean_G_x)\n L2_G2_x_mean = np.mean(L2_mean_G_x)\n L2_G2_x_std = np.std(L2_mean_G_x)\n print('ssim_G2_x_mean: %f\\n' % ssim_G2_x_mean)\n print('ssim_G2_x_std: %f\\n' % ssim_G2_x_std)\n print('psnr_G2_x_mean: %f\\n' % psnr_G2_x_mean)\n print('psnr_G2_x_std: %f\\n' % psnr_G2_x_std)\n print('L1_G2_x_mean: %f\\n' % L1_G2_x_mean)\n print('L1_G2_x_std: %f\\n' % L1_G2_x_std)\n print('L2_G2_x_mean: %f\\n' % L2_G2_x_mean)\n print('L2_G2_x_std: %f\\n' % L2_G2_x_std)\n\n ##################### Inception score ##################\n G1_list_masked = [np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*G1_list[i]) for i in range(len(G1_list))]\n G2_list_masked = [np.uint8(mask_target_list[i][:,:,np.newaxis]/255.*G2_list[i]) for i in range(len(G2_list))]\n # IS_G1_mean, IS_G1_std = tflib.inception_score.get_inception_score(G1_list)\n IS_G1_mean, IS_G1_std = tflib.inception_score.get_inception_score(G1_list_masked)\n print('IS_G1_mean: %f\\n' % IS_G1_mean)\n print('IS_G1_std: %f\\n' % IS_G1_std)\n # IS_G2_mean, IS_G2_std = tflib.inception_score.get_inception_score(G2_list)\n IS_G2_mean, IS_G2_std = tflib.inception_score.get_inception_score(G2_list_masked)\n print('IS_G2_mean: %f\\n' % IS_G2_mean)\n print('IS_G2_std: %f\\n' % IS_G2_std)\n\n with open(score_path, 'w') as f:\n f.write('N: %d ' % N)\n f.write('ssimG1: %.5f +- %.5f ' % (ssim_G1_x_mean, ssim_G1_x_std))\n f.write('ISG1: %.5f +- %.5f ' % (IS_G1_mean, IS_G1_std))\n f.write('psnrG1: %.5f +- %.5f ' % (psnr_G1_x_mean, psnr_G1_x_std))\n f.write('L1G1: %.5f +- %.5f ' % (L1_G1_x_mean, L1_G1_x_std))\n f.write('L2G1: %.5f +- %.5f ' % (L2_G1_x_mean, L2_G1_x_std))\n f.write('ssimG2: %.5f +- %.5f ' % (ssim_G2_x_mean, ssim_G2_x_std))\n f.write('ISG2: %.5f +- %.5f ' % (IS_G2_mean, IS_G2_std))\n f.write('psnrG2: %.5f +- %.5f ' % (psnr_G2_x_mean, psnr_G2_x_std))\n f.write('L1G2: %.5f +- %.5f ' % (L1_G2_x_mean, L1_G2_x_std))\n f.write('L2G2: %.5f +- %.5f' % (L2_G2_x_mean, L2_G2_x_std))\n\n\n\n # f.write('ssim_std: %f ' % ssim_G_x_std)\n # f.write('IS_mean: %f ' % IS_G_mean)\n # f.write('IS_std: %f ' % IS_G_std)\n # f.write('psnr_mean: %f ' % psnr_G_x_mean)\n # f.write('psnr_std: %f' % psnr_G_x_std)\n" ]
[ [ "numpy.product", "numpy.abs", "numpy.uint8", "numpy.std", "numpy.mean", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fogx/docarray
[ "2cb60f893ebcfd29708132e44202ccb20e639c6b" ]
[ "tests/unit/document/test_converters.py" ]
[ "import os\n\nimport numpy as np\nimport pytest\n\nfrom docarray import Document\nfrom docarray.document.generators import from_files\nfrom docarray.helper import __windows__\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\n\ndef test_video_convert_pipe(pytestconfig, tmpdir):\n num_d = 0\n fname = str(tmpdir / f'tmp{num_d}.mp4')\n d = Document(uri=os.path.join(cur_dir, 'toydata/mov_bbb.mp4'))\n d.load_uri_to_video_tensor()\n d.save_video_tensor_to_file(fname)\n assert os.path.exists(fname)\n\n\ndef test_audio_convert_pipe(pytestconfig, tmpdir):\n num_d = 0\n for d in from_files(f'{cur_dir}/toydata/*.wav'):\n fname = str(tmpdir / f'tmp{num_d}.wav')\n d.load_uri_to_audio_tensor()\n d.tensor = d.tensor[::-1]\n d.save_audio_tensor_to_file(fname)\n assert os.path.exists(fname)\n num_d += 1\n assert num_d\n\n\ndef test_image_convert_pipe(pytestconfig):\n for d in from_files(f'{pytestconfig.rootdir}/.github/**/*.png'):\n (\n d.load_uri_to_image_tensor()\n .convert_uri_to_datauri()\n .set_image_tensor_shape((64, 64))\n .set_image_tensor_normalization()\n .set_image_tensor_channel_axis(-1, 0)\n )\n assert d.tensor.shape == (3, 64, 64)\n assert d.uri\n\n\ndef test_uri_to_tensor():\n doc = Document(uri=os.path.join(cur_dir, 'toydata/test.png'))\n doc.load_uri_to_image_tensor()\n assert isinstance(doc.tensor, np.ndarray)\n assert doc.tensor.shape == (85, 152, 3) # h,w,c\n assert doc.mime_type == 'image/png'\n\n\ndef test_datauri_to_tensor():\n doc = Document(uri=os.path.join(cur_dir, 'toydata/test.png'))\n doc.convert_uri_to_datauri()\n assert not doc.tensor\n assert doc.mime_type == 'image/png'\n\n\ndef test_blob_to_tensor():\n doc = Document(uri=os.path.join(cur_dir, 'toydata/test.png'))\n doc.load_uri_to_blob()\n doc.convert_blob_to_image_tensor()\n assert isinstance(doc.tensor, np.ndarray)\n assert doc.mime_type == 'image/png'\n assert doc.tensor.shape == (85, 152, 3) # h,w,c\n\n\ndef test_convert_blob_to_tensor():\n rand_state = np.random.RandomState(0)\n array = rand_state.random([10, 10])\n doc = Document(content=array.tobytes())\n assert doc.content_type == 'blob'\n intialiazed_blob = doc.blob\n\n doc.convert_blob_to_tensor()\n assert doc.content_type == 'tensor'\n converted_blob_in_one_of = doc.blob\n assert intialiazed_blob != converted_blob_in_one_of\n np.testing.assert_almost_equal(doc.content.reshape([10, 10]), array)\n\n\[email protected]('shape, channel_axis', [((3, 32, 32), 0), ((32, 32, 3), -1)])\ndef test_image_normalize(shape, channel_axis):\n doc = Document(content=np.random.randint(0, 255, shape, dtype=np.uint8))\n doc.set_image_tensor_normalization(channel_axis=channel_axis)\n assert doc.tensor.ndim == 3\n assert doc.tensor.shape == shape\n assert doc.tensor.dtype == np.float32\n\n\[email protected](\n 'arr_size, channel_axis, height, width',\n [\n ([32, 28, 3], -1, 32, 28), # h, w, c (rgb)\n ([3, 32, 28], 0, 32, 28), # c, h, w (rgb)\n ([1, 32, 28], 0, 32, 28), # c, h, w, (greyscale)\n ([32, 28, 1], -1, 32, 28), # h, w, c, (greyscale)\n ],\n)\ndef test_convert_image_tensor_to_uri(arr_size, channel_axis, width, height):\n doc = Document(content=np.random.randint(0, 255, arr_size))\n assert doc.tensor.any()\n assert not doc.uri\n doc.set_image_tensor_shape(channel_axis=channel_axis, shape=(width, height))\n\n doc.convert_image_tensor_to_uri(channel_axis=channel_axis)\n assert doc.uri.startswith('data:image/png;base64,')\n assert doc.mime_type == 'image/png'\n assert doc.tensor.any() # assure after conversion tensor still exist.\n\n\[email protected](\n condition=__windows__, reason='x-python is not detected on windows CI'\n)\[email protected](\n 'uri, mimetype',\n [\n (__file__, 'text/x-python'),\n ('http://google.com/index.html', 'text/html'),\n ('https://google.com/index.html', 'text/html'),\n ],\n)\ndef test_convert_uri_to_blob(uri, mimetype):\n d = Document(uri=uri)\n assert not d.blob\n d.load_uri_to_blob()\n assert d.blob\n assert d.mime_type == mimetype\n\n\[email protected](\n 'converter', ['convert_blob_to_datauri', 'convert_content_to_datauri']\n)\ndef test_convert_blob_to_uri(converter):\n d = Document(content=open(__file__).read().encode(), mime_type='text/x-python')\n assert d.blob\n getattr(d, converter)()\n assert d.uri.startswith('data:text/x-python;')\n\n\[email protected](\n 'converter', ['convert_text_to_datauri', 'convert_content_to_datauri']\n)\ndef test_convert_text_to_uri(converter):\n d = Document(content=open(__file__).read())\n assert d.text\n getattr(d, converter)()\n assert d.uri.startswith('data:text/plain;')\n\n\[email protected](\n condition=__windows__, reason='x-python is not detected on windows CI'\n)\[email protected](\n 'uri, mimetype',\n [\n pytest.param(\n __file__,\n 'text/x-python',\n marks=pytest.mark.xfail(\n condition=__windows__, reason='x-python is not detected on windows CI'\n ),\n ),\n ('http://google.com/index.html', 'text/html'),\n ('https://google.com/index.html', 'text/html'),\n ],\n)\ndef test_convert_uri_to_text(uri, mimetype):\n doc = Document(uri=uri, mime_type=mimetype)\n doc.load_uri_to_text()\n if mimetype == 'text/html':\n assert '<!doctype html>' in doc.text\n elif mimetype == 'text/x-python':\n text_from_file = open(__file__).read()\n assert doc.text == text_from_file\n\n\ndef test_convert_text_to_uri_and_back():\n text_from_file = open(__file__).read()\n doc = Document(content=text_from_file, mime_type='text/x-python')\n assert doc.text\n assert doc.mime_type == 'text/x-python'\n doc.convert_text_to_datauri()\n doc.load_uri_to_text()\n assert doc.mime_type == 'text/plain'\n assert doc.text == text_from_file\n\n\ndef test_convert_text_diff_encoding(tmpfile):\n otext = 'testä'\n text = otext.encode('iso8859')\n with open(tmpfile, 'wb') as fp:\n fp.write(text)\n with pytest.raises(UnicodeDecodeError):\n d = Document(uri=str(tmpfile)).load_uri_to_text()\n\n d = Document(uri=str(tmpfile)).load_uri_to_text(charset='iso8859')\n assert d.text == otext\n\n with open(tmpfile, 'w', encoding='iso8859') as fp:\n fp.write(otext)\n with pytest.raises(UnicodeDecodeError):\n d = Document(uri=str(tmpfile)).load_uri_to_text()\n\n d = Document(uri=str(tmpfile)).load_uri_to_text(charset='iso8859')\n assert d.text == otext\n\n\ndef test_convert_content_to_uri():\n d = Document(content=np.random.random([10, 10]))\n with pytest.raises(NotImplementedError):\n d.convert_content_to_datauri()\n\n\[email protected](\n 'uri, mimetype',\n [\n (__file__, 'text/x-python'),\n ('http://google.com/index.html', 'text/html'),\n ('https://google.com/index.html', 'text/html'),\n ],\n)\ndef test_convert_uri_to_data_uri(uri, mimetype):\n doc = Document(uri=uri, mime_type=mimetype)\n doc.convert_uri_to_datauri()\n assert doc.uri.startswith(f'data:{mimetype}')\n assert doc.mime_type == mimetype\n\n\ndef test_glb_converters():\n doc = Document(uri=os.path.join(cur_dir, 'toydata/test.glb'))\n doc.load_uri_to_point_cloud_tensor(2000)\n assert doc.tensor.shape == (2000, 3)\n\n doc.load_uri_to_point_cloud_tensor(2000, as_chunks=True)\n assert len(doc.chunks) == 1\n assert doc.chunks[0].tensor.shape == (2000, 3)\n" ]
[ [ "numpy.random.RandomState", "numpy.random.random", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mevalle/r-DEP-Classifier
[ "c18625fe6b69ec9cc4edead7bb7f647ebf71956a" ]
[ "rDEP.py" ]
[ "import numpy as np\nimport cvxpy as cp\nimport dccp\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\nfrom sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin\nfrom sklearn.utils.multiclass import unique_labels\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.utils.validation import check_X_y, check_array, check_is_fitted\nfrom sklearn.model_selection import StratifiedKFold\nimport time\n\n# ##################################################\n# Plot the decision boundary of a classifier\n# ##################################################\n\ndef decision_boundary(self, X, y, ind=[0,1], Nh = 101, colors=\"black\", label = None): \n # Scatter plot\n sc = plt.scatter(X[:,ind[0]], X[:,ind[1]], c = y.astype(int))\n xlimits = plt.xlim()\n ylimits = plt.ylim()\n \n if X.shape[1]>2:\n print(\"Dimension larger than two! Cannot show the decision boundary!\")\n else:\n # create a mesh to plot in\n x_min, x_max = xlimits[0], xlimits[1]\n y_min, y_max = ylimits[0], ylimits[1]\n hx = (x_max-x_min)/Nh\n hy = (y_max-y_min)/Nh\n xx, yy = np.meshgrid(np.arange(x_min, x_max, hx),np.arange(y_min, y_max, hy))\n \n # Plot the decision boundary. For that, we will assign a color to each\n # point in the mesh [x_min, m_max]x[y_min, y_max].\n Z = np.array(self.predict(np.c_[xx.ravel(), yy.ravel()]))\n Z = Z.reshape(xx.shape)\n \n # Put the result into a color plot\n plt.contourf(xx, yy, Z, alpha = 0.1, cmap='plasma')\n plt.contour(xx, yy, Z, colors=colors, linestyles = 'dashed')\n \n plt.grid(\"True\")\n plt.xlabel(\"Variable %d\" % ind[0])\n plt.ylabel(\"Variable %d\" % ind[1])\n return sc\n\n# ##################################################\n# Ensemble (or Bagging) Transform\n# ##################################################\nclass EnsembleTransform(TransformerMixin, BaseEstimator):\n def __init__(self,ensemble):\n self.ensemble = ensemble\n \n def fit(self, X, y):\n (self.ensemble).fit(X, y)\n return self\n \n def transform(self, X):\n return np.vstack([clf.decision_function(X) for clf in (self.ensemble).estimators_]).T\n\n\n# ##################################################\n# Dilation-Erosion Perceptron with DCCP\n# ################################################## \nclass DEP(BaseEstimator, ClassifierMixin):\n \n def __init__(self, weighted = True, ref = \"maximum\", C = 1.e-2, \n beta = None, beta_loss = \"hinge\", Split2Beta = False, \n solver = cp.MOSEK, verbose = False):\n self.verbose = verbose\n self.solver = solver\n self.weighted = weighted\n self.ref = ref\n self.C = C\n self.beta = beta\n self.beta_loss = beta_loss\n self.Split2Beta = Split2Beta\n \n def fit(self, X, y):\n start_time = time.time()\n \n # Check that X and y have correct shape\n X, y = check_X_y(X, y)\n \n # Store the classes seen during fit\n self.classes_ = unique_labels(y)\n \n if len(self.classes_)>2:\n print(\"Dilation-Erosion Morphological Perceptron can be used for binary classification!\")\n return \n \n if self.Split2Beta == True:\n skf = StratifiedKFold(n_splits=3, shuffle=True)\n WM_index, beta_index = next(iter(skf.split(X,y)))\n X_WM, X_beta = X[WM_index], X[beta_index]\n y_WM, y_beta = y[WM_index], y[beta_index]\n else:\n X_WM, X_beta = X, X\n y_WM, y_beta = y, y\n \n M, N = X_beta.shape\n \n indPos = (y_WM == self.classes_[1])\n Xpos = X_WM[indPos,:]\n Xneg = X_WM[~indPos,:]\n Mpos = Xpos.shape[0]\n Mneg = Xneg.shape[0]\n\n if self.weighted == True:\n Lpos = 1/pairwise_distances(Xpos,[np.mean(Xpos,axis=0)],metric=\"euclidean\").flatten()\n Lneg = 1/pairwise_distances(Xneg,[np.mean(Xneg,axis=0)],metric=\"euclidean\").flatten()\n nuPos = Lpos/Lpos.max()\n nuNeg = Lneg/Lneg.max()\n else:\n nuPos = np.ones((Mpos))\n nuNeg = np.ones((Mneg))\n \n # Solve DCCP problem for dilation\n if self.ref == \"mean\":\n ref = -np.mean(Xneg,axis=0).reshape((1,N))\n elif self.ref == \"maximum\":\n ref = -np.max(Xneg,axis=0).reshape((1,N))\n elif self.ref == \"minimum\":\n ref = -np.min(Xneg,axis=0).reshape((1,N))\n else:\n ref = np.zeros((1,N))\n \n w = cp.Variable((1,N))\n xiPos = cp.Variable((Mpos))\n xiNeg = cp.Variable((Mneg))\n \n lossDil = cp.sum(nuPos*cp.pos(xiPos))/Mpos+cp.sum(nuNeg*cp.pos(xiNeg))/Mneg+self.C*cp.norm(w-ref,1)\n objectiveDil = cp.Minimize(lossDil)\n \n ZposDil = cp.max(np.ones((Mpos,1))@w + Xpos, axis=1)\n ZnegDil = cp.max(np.ones((Mneg,1))@w + Xneg, axis=1) \n constraintsDil = [ZposDil >= -xiPos, ZnegDil <= xiNeg]\n\n probDil = cp.Problem(objectiveDil,constraintsDil) \n probDil.solve(solver=self.solver, method = 'dccp', verbose = self.verbose)\n self.dil_ = (w.value).flatten()\n \n # Solve DCCP problem for erosion\n if self.ref == \"mean\":\n ref = -np.mean(Xpos,axis=0).reshape((1,N))\n elif self.ref == \"maximum\":\n ref = -np.min(Xpos,axis=0).reshape((1,N))\n elif self.ref == \"minimum\":\n ref = -np.max(Xpos,axis=0).reshape((1,N))\n else:\n ref = np.zeros((1,N))\n \n m = cp.Variable((1,N))\n etaPos = cp.Variable((Mpos))\n etaNeg = cp.Variable((Mneg))\n \n lossEro = cp.sum(nuPos*cp.pos(etaPos))/Mpos+cp.sum(nuNeg*cp.pos(etaNeg))/Mneg+self.C*cp.norm(m-ref,1)\n objectiveEro = cp.Minimize(lossEro)\n \n ZposEro = cp.min(np.ones((Mpos,1))@m + Xpos, axis=1)\n ZnegEro = cp.min(np.ones((Mneg,1))@m + Xneg, axis=1) \n constraintsEro = [ZposEro >= -etaPos, ZnegEro <= etaNeg]\n\n probEro = cp.Problem(objectiveEro,constraintsEro) \n probEro.solve(solver=self.solver, method = 'dccp', verbose = self.verbose)\n self.ero_ = (m.value).flatten()\n \n # Fine tune beta\n if self.beta == None:\n beta = cp.Variable(nonneg=True)\n beta.value = 0.5\n \n if self.beta_loss == \"squared_hinge\":\n # Squared Hinge Loss\n lossBeta = cp.sum_squares(cp.pos(-cp.multiply(2*((y_beta == self.classes_[1]).astype(int))-1,\n beta*cp.max(np.ones((M,1))@w.value + X_beta, axis=1) +\n (1-beta)*cp.min(np.ones((M,1))@m.value + X_beta, axis=1))))\n else:\n # Hinge Loss\n lossBeta = cp.sum(cp.pos(-cp.multiply(2*((y_beta == self.classes_[1]).astype(int))-1,\n beta*cp.max(np.ones((M,1))@w.value + X_beta, axis=1) +\n (1-beta)*cp.min(np.ones((M,1))@m.value + X_beta, axis=1))))\n \n constraintsBeta = [beta<=1]\n probBeta = cp.Problem(cp.Minimize(lossBeta),constraintsBeta)\n probBeta.solve(solver = cp.SCS, verbose = self.verbose, warm_start=True)\n self.beta = beta.value\n \n if self.verbose == True:\n print(\"\\nTime to train: %2.2f seconds.\" % (time.time() - start_time))\n return self\n \n def decision_function(self, X):\n # Check is fit had been called\n check_is_fitted(self,attributes=\"dil_\")\n \n # Input validation\n X = check_array(X)\n \n M,N = X.shape\n Y = np.zeros((M,2))\n # Compute the dilation\n Y[:,0] = np.amax(np.ones((M,1))@self.dil_.reshape((1,N))+X,axis=1)\n # Compute the erosion\n Y[:,1] = np.amin(np.ones((M,1))@self.ero_.reshape((1,N))+X,axis=1)\n \n return np.dot(Y,np.array([self.beta,1-self.beta]))\n \n def predict(self, X):\n return np.array([self.classes_[(y>=0).astype(int)] for y in self.decision_function(X)])\n\n def show(self, X, y, ind=[0,1], show_boxes = True, decision_boundary = True, Nh = 101):\n # Check that X and y have correct shape\n X, y = check_X_y(X, y)\n\n # Check is fit had been called\n check_is_fitted(self,attributes=\"dil_\")\n\n plt.figure(figsize=(10, 8))\n \n # Scatter plot\n sc = plt.scatter(X[:,ind[0]], X[:,ind[1]], c = y.astype(int))\n xlimits = plt.xlim()\n ylimits = plt.ylim()\n \n if decision_boundary:\n if X.shape[1]>2:\n print(\"Dimension larger than two! Cannot show the decision boundary!\")\n else:\n # create a mesh to plot in\n x_min, x_max = xlimits[0], xlimits[1]\n y_min, y_max = ylimits[0], ylimits[1]\n hx = (x_max-x_min)/Nh\n hy = (y_max-y_min)/Nh\n xx, yy = np.meshgrid(np.arange(x_min, x_max, hx),np.arange(y_min, y_max, hy))\n \n # Plot the decision boundary. For that, we will assign a color to each\n # point in the mesh [x_min, m_max]x[y_min, y_max].\n Z = np.array(self.predict(np.c_[xx.ravel(), yy.ravel()]))\n Z = Z.reshape(xx.shape)\n \n # Put the result into a color plot\n plt.contourf(xx, yy, Z, alpha = 0.1, cmap='plasma')\n plt.contour(xx, yy, Z, colors='black', linestyles = 'dashed')\n \n if show_boxes:\n # Draw dilation box\n box = [-1000*np.ones((X.shape[1],)),-self.dil_]\n Vertices = np.array([box[0][ind],[box[1][ind[0]],box[0][ind[1]]],box[1][ind],[box[0][ind[0]],box[1][ind[1]]]])\n plt.gca().add_patch(Polygon(Vertices, alpha = 0.3, color=sc.to_rgba(0)))\n \n # Draw erosion box\n box = [-self.ero_,1000*np.ones((X.shape[1],))]\n Vertices = np.array([box[0][ind],[box[1][ind[0]],box[0][ind[1]]],box[1][ind],[box[0][ind[0]],box[1][ind[1]]]])\n plt.gca().add_patch(Polygon(Vertices, alpha = 0.3, color=sc.to_rgba(1)))\n \n plt.grid(True)\n plt.xlabel(\"Variable %d\" % ind[0])\n plt.ylabel(\"Variable %d\" % ind[1])\n" ]
[ [ "matplotlib.pyplot.contourf", "sklearn.utils.validation.check_is_fitted", "numpy.max", "numpy.mean", "matplotlib.pyplot.gca", "numpy.arange", "sklearn.model_selection.StratifiedKFold", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.min", "matplotlib.pyplot.ylim", "sklearn.utils.validation.check_X_y", "numpy.array", "sklearn.utils.multiclass.unique_labels", "matplotlib.pyplot.ylabel", "sklearn.utils.validation.check_array", "numpy.ones", "matplotlib.pyplot.xlim", "matplotlib.pyplot.contour", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zzdxfei/detectron_cascade_code
[ "59706f1687ee067d1df5da60e7a4a442fb2d59f8" ]
[ "detectron/ops/distribute_cascade_proposals.py" ]
[ "# Copyright (c) 2017-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\n\nfrom detectron.core.config import cfg\nfrom detectron.datasets import json_dataset\nimport detectron.modeling.FPN as fpn\nimport detectron.roi_data.cascade_rcnn as cascade_rcnn_roi_data\nimport detectron.utils.blob as blob_utils\n\n\nclass DistributeCascadeProposalsOp(object):\n\n def __init__(self, train, stage):\n self._train = train\n self._stage = stage\n\n def forward(self, inputs, outputs):\n \"\"\"See modeling.detector.DistributeCascadeProposals for\n inputs/outputs documentation.\n \"\"\"\n rois = inputs[0].data\n if self._train:\n # During training we reuse the data loader code. We populate roidb\n # entries on the fly using the rois generated by RPN.\n # im_info: [[im_height, im_width, im_scale], ...]\n roidb = blob_utils.deserialize(inputs[1].data)\n im_info = inputs[2].data\n im_scales = im_info[:, 2]\n\n # For historical consistency with the original Faster R-CNN\n # implementation we are *not* filtering crowd proposals.\n # This choice should be investigated in the future (it likely does\n # not matter).\n json_dataset.add_proposals(roidb, rois, im_scales, crowd_thresh=0)\n # Compute training labels for the RPN proposals; also handles\n # distributing the proposals over FPN levels\n output_blob_names = cascade_rcnn_roi_data.get_cascade_rcnn_blob_names(\n self._stage\n )\n blobs = {k: [] for k in output_blob_names}\n\n # 进行rois映射到了合适的fpn层, 并重新进行采样构成训练数据\n cascade_rcnn_roi_data.add_cascade_rcnn_blobs(\n blobs, im_scales, roidb, self._stage\n )\n for i, k in enumerate(output_blob_names):\n blob_utils.py_op_copy_blob(blobs[k], outputs[i])\n else:\n # For inference we have a special code path that avoids some data\n # loader overhead\n distribute(rois, None, outputs, self._train)\n\n\ndef distribute(rois, label_blobs, outputs, train):\n \"\"\"To understand the output blob order see return value of\n roi_data.cascade_rcnn.get_cascade_rcnn_blob_names(is_training=False)\n \"\"\"\n lvl_min = cfg.FPN.ROI_MIN_LEVEL\n lvl_max = cfg.FPN.ROI_MAX_LEVEL\n lvls = fpn.map_rois_to_fpn_levels(rois[:, 1:5], lvl_min, lvl_max)\n\n outputs[0].reshape(rois.shape)\n outputs[0].data[...] = rois\n\n # Create new roi blobs for each FPN level\n # (See: modeling.FPN.add_multilevel_roi_blobs which is similar but annoying\n # to generalize to support this particular case.)\n rois_idx_order = np.empty((0,))\n for output_idx, lvl in enumerate(range(lvl_min, lvl_max + 1)):\n idx_lvl = np.where(lvls == lvl)[0]\n blob_roi_level = rois[idx_lvl, :]\n outputs[output_idx + 1].reshape(blob_roi_level.shape)\n outputs[output_idx + 1].data[...] = blob_roi_level\n rois_idx_order = np.concatenate((rois_idx_order, idx_lvl))\n rois_idx_restore = np.argsort(rois_idx_order)\n blob_utils.py_op_copy_blob(rois_idx_restore.astype(np.int32), outputs[-1])\n" ]
[ [ "numpy.concatenate", "numpy.argsort", "numpy.where", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
iamchosenlee/MolDQN-pytorch
[ "bda8a74eb9e5d2f3232a6a27b6a32928a3797f6d" ]
[ "dqn.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass MolDQN(nn.Module):\n def __init__(self, input_length, output_length):\n super(MolDQN, self).__init__()\n\n self.linear_1 = nn.Linear(input_length, 1024)\n self.linear_2 = nn.Linear(1024, 512)\n self.linear_3 = nn.Linear(512, 128)\n self.linear_4 = nn.Linear(128, 32)\n self.linear_5 = nn.Linear(32, output_length)\n\n self.activation = nn.ReLU()\n\n def forward(self, x):\n x = self.activation(self.linear_1(x))\n x = self.activation(self.linear_2(x))\n x = self.activation(self.linear_3(x))\n x = self.activation(self.linear_4(x))\n x = self.linear_5(x)\n\n return x\n" ]
[ [ "torch.nn.Linear", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
markqiu/zvt
[ "1bcfb71279f2652c3600f0f8e45d941f98ceaa10", "23105a5bfdc3a5080c6c22d11e9e53d216688dea" ]
[ "zvt/recorders/joinquant/meta/china_stock_status_recorder.py", "zvt/recorders/exchange/china_index_list_spider.py" ]
[ "# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom jqdatasdk import auth, logout, finance, query\nfrom zvt.recorders.joinquant.common import to_jq_entity_id\n\nfrom zvt import zvt_env\nfrom zvt.api import TIME_FORMAT_DAY, get_str_schema\nfrom zvt.contract.api import df_to_db\nfrom zvt.contract.recorder import TimeSeriesDataRecorder\nfrom zvt.domain import StockDetail,StockStatus\n\nfrom zvt.utils.pd_utils import pd_is_not_null\nfrom zvt.utils.time_utils import now_pd_timestamp, to_time_str\n\nclass JqChinaStockStatusRecorder(TimeSeriesDataRecorder):\n entity_provider = 'joinquant'\n entity_schema = StockDetail\n\n # 数据来自jq\n provider = 'joinquant'\n\n data_schema = StockStatus\n\n def __init__(self, entity_type='stock', exchanges=['sh', 'sz'], entity_ids=None, codes=None, batch_size=10,\n force_update=False, sleeping_time=5, default_size=2000, real_time=False,\n fix_duplicate_way='add', start_timestamp=None, end_timestamp=None, close_hour=0,\n close_minute=0) -> None:\n self.data_schema = StockStatus\n super().__init__(entity_type, exchanges, entity_ids, codes, batch_size, force_update, sleeping_time,\n default_size, real_time, fix_duplicate_way, start_timestamp, end_timestamp, close_hour,\n close_minute)\n # 调用登录函数(激活后使用,不需要用户名密码)\n auth(zvt_env['jq_username'], zvt_env['jq_password'])\n\n def on_finish(self):\n super().on_finish()\n logout()\n\n def record(self, entity, start, end, size, timestamps):\n if not end:\n end = to_time_str(now_pd_timestamp())\n start = to_time_str(start)\n q = query(finance.STK_STATUS_CHANGE).filter(\n finance.STK_STATUS_CHANGE.code == to_jq_entity_id(entity)).filter(\n finance.STK_STATUS_CHANGE.pub_date >= to_time_str(start)).limit(10)\n df = finance.run_query(q)\n\n if pd_is_not_null(df):\n df['pub_date'] = pd.to_datetime(df['pub_date'])\n df['exchange'] = entity.exchange\n df['entity_type'] = entity.entity_type\n df['change_date'] = pd.to_datetime(df['change_date'])\n df['timestamp'] = df['change_date']\n\n df['entity_id'] = entity.id\n df['provider'] = 'joinquant'\n df['code'] = entity.code\n\n def generate_finance_id(se):\n return \"{}_{}\".format(se['entity_id'], to_time_str(se['timestamp'], fmt=TIME_FORMAT_DAY))\n\n df['id'] = df[['entity_id', 'timestamp']].apply(generate_finance_id, axis=1)\n\n df_to_db(df=df, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update)\n return None\n\n__all__ = ['JqChinaStockStatusRecorder']\n", "# -*- coding: utf-8 -*-\n\nimport io\n\nimport demjson\nimport pandas as pd\nimport requests\n\nfrom zvt.contract.api import df_to_db\nfrom zvt.contract.recorder import Recorder\nfrom zvt.utils.time_utils import to_pd_timestamp, now_pd_timestamp\nfrom zvt.api.quote import china_stock_code_to_id\nfrom zvt.domain import IndexStock, Index\n\n\nclass ChinaIndexListSpider(Recorder):\n data_schema = IndexStock\n\n def __init__(self, batch_size=10, force_update=False, sleeping_time=2.0, provider='exchange') -> None:\n self.provider = provider\n super().__init__(batch_size, force_update, sleeping_time)\n\n def run(self):\n # 上证、中证\n self.fetch_csi_index()\n\n # 深证\n # self.fetch_szse_index()\n\n # 国证\n # FIXME:已不可用\n # self.fetch_cni_index()\n\n def fetch_csi_index(self) -> None:\n \"\"\"\n 抓取上证、中证指数列表\n \"\"\"\n url = 'http://www.csindex.com.cn/zh-CN/indices/index' \\\n '?page={}&page_size={}&data_type=json&class_1=1&class_2=2&class_7=7&class_10=10'\n\n index_list = []\n page = 1\n page_size = 50\n while True:\n query_url = url.format(page, page_size)\n response = requests.get(query_url)\n response_dict = demjson.decode(response.text)\n response_index_list = response_dict.get('list', [])\n\n if len(response_index_list) == 0:\n break\n\n index_list.extend(response_index_list)\n\n self.logger.info(f'上证、中证指数第 {page} 页抓取完成...')\n page += 1\n self.sleep()\n\n df = pd.DataFrame(index_list)\n df = df[['base_date', 'base_point', 'index_code', 'indx_sname', 'online_date', 'class_eseries']].copy()\n df.columns = ['timestamp', 'base_point', 'code', 'name', 'list_date', 'class_eseries']\n df['category'] = df['class_eseries'].apply(lambda x: x.split(' ')[0].lower())\n df = df.drop('class_eseries', axis=1)\n df = df.loc[df['code'].str.contains(r'^\\d{6}$')]\n\n self.persist_index(df)\n self.logger.info('上证、中证指数列表抓取完成...')\n\n # 抓取上证、中证指数成分股\n self.fetch_csi_index_component(df)\n self.logger.info('上证、中证指数成分股抓取完成...')\n\n def fetch_csi_index_component(self, df: pd.DataFrame):\n \"\"\"\n 抓取上证、中证指数成分股\n \"\"\"\n query_url = 'http://www.csindex.com.cn/uploads/file/autofile/cons/{}cons.xls'\n\n for _, index in df.iterrows():\n index_code = index['code']\n\n url = query_url.format(index_code)\n\n try:\n response = requests.get(url)\n response.raise_for_status()\n except requests.HTTPError as error:\n self.logger.error(f'{index[\"name\"]} - {index_code} 成分股抓取错误 ({error})')\n continue\n\n response_df = pd.read_excel(io.BytesIO(response.content))\n\n response_df = response_df[['成分券代码Constituent Code', '成分券名称Constituent Name']].rename(\n columns={'成分券代码Constituent Code': 'stock_code',\n '成分券名称Constituent Name': 'stock_name'})\n\n index_id = f'index_cn_{index_code}'\n response_df['entity_id'] = index_id\n response_df['entity_type'] = 'index'\n response_df['exchange'] = 'cn'\n response_df['code'] = index_code\n response_df['name'] = index['name']\n response_df['timestamp'] = now_pd_timestamp()\n\n response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x)))\n response_df['id'] = response_df['stock_id'].apply(\n lambda x: f'{index_id}_{x}')\n\n df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider, force_update=True)\n self.logger.info(f'{index[\"name\"]} - {index_code} 成分股抓取完成...')\n\n self.sleep()\n\n def fetch_szse_index(self) -> None:\n \"\"\"\n 抓取深证指数列表\n \"\"\"\n url = 'http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1812_zs&TABKEY=tab1'\n response = requests.get(url)\n df = pd.read_excel(io.BytesIO(response.content), dtype='str')\n\n df.columns = ['code', 'name', 'timestamp', 'base_point', 'list_date']\n df['category'] = 'szse'\n df = df.loc[df['code'].str.contains(r'^\\d{6}$')]\n self.persist_index(df)\n self.logger.info('深证指数列表抓取完成...')\n\n # 抓取深证指数成分股\n self.fetch_szse_index_component(df)\n self.logger.info('深证指数成分股抓取完成...')\n\n def fetch_szse_index_component(self, df: pd.DataFrame):\n \"\"\"\n 抓取深证指数成分股\n \"\"\"\n query_url = 'http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1747_zs&TABKEY=tab1&ZSDM={}'\n\n for _, index in df.iterrows():\n index_code = index['code']\n\n url = query_url.format(index_code)\n response = requests.get(url)\n\n response_df = pd.read_excel(io.BytesIO(response.content), dtype='str')\n\n index_id = f'index_cn_{index_code}'\n response_df['entity_id'] = index_id\n response_df['entity_type'] = 'index'\n response_df['exchange'] = 'cn'\n response_df['code'] = index_code\n response_df['name'] = index['name']\n response_df['timestamp'] = now_pd_timestamp()\n\n response_df.rename(columns={'证券代码': 'stock_code', '证券简称': 'stock_name'}, inplace=True)\n response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x)))\n\n response_df['id'] = response_df['stock_id'].apply(\n lambda x: f'{index_id}_{x}')\n\n df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider)\n self.logger.info(f'{index[\"name\"]} - {index_code} 成分股抓取完成...')\n\n self.sleep()\n\n def fetch_cni_index(self) -> None:\n \"\"\"\n 抓取国证指数列表\n \"\"\"\n url = 'http://www.cnindex.com.cn/zstx/jcxl/'\n response = requests.get(url)\n response.encoding = 'utf-8'\n dfs = pd.read_html(response.text)\n\n # 第 9 个 table 之后为非股票指数\n dfs = dfs[1:9]\n\n result_df = pd.DataFrame()\n for df in dfs:\n header = df.iloc[0]\n df = df[1:]\n df.columns = header\n df.astype('str')\n\n result_df = pd.concat([result_df, df])\n\n result_df = result_df.drop('样本股数量', axis=1)\n result_df.columns = ['name', 'code', 'timestamp', 'base_point', 'list_date']\n result_df['timestamp'] = result_df['timestamp'].apply(lambda x: x.replace('-', ''))\n result_df['list_date'] = result_df['list_date'].apply(lambda x: x.replace('-', ''))\n result_df['category'] = 'csi'\n result_df = result_df.loc[result_df['code'].str.contains(r'^\\d{6}$')]\n\n self.persist_index(result_df)\n self.logger.info('国证指数列表抓取完成...')\n\n # 抓取国证指数成分股\n self.fetch_cni_index_component(result_df)\n self.logger.info('国证指数成分股抓取完成...')\n\n def fetch_cni_index_component(self, df: pd.DataFrame):\n \"\"\"\n 抓取国证指数成分股\n \"\"\"\n query_url = 'http://www.cnindex.com.cn/docs/yb_{}.xls'\n\n for _, index in df.iterrows():\n index_code = index['code']\n\n url = query_url.format(index_code)\n\n try:\n response = requests.get(url)\n response.raise_for_status()\n except requests.HTTPError as error:\n self.logger.error(f'{index[\"name\"]} - {index_code} 成分股抓取错误 ({error})')\n continue\n\n response_df = pd.read_excel(io.BytesIO(response.content), dtype='str')\n\n index_id = f'index_cn_{index_code}'\n\n try:\n response_df = response_df[['样本股代码']]\n except KeyError:\n response_df = response_df[['证券代码']]\n\n response_df['entity_id'] = index_id\n response_df['entity_type'] = 'index'\n response_df['exchange'] = 'cn'\n response_df['code'] = index_code\n response_df['name'] = index['name']\n response_df['timestamp'] = now_pd_timestamp()\n\n response_df.columns = ['stock_code']\n response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x)))\n response_df['id'] = response_df['stock_id'].apply(\n lambda x: f'{index_id}_{x}')\n\n df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider)\n self.logger.info(f'{index[\"name\"]} - {index_code} 成分股抓取完成...')\n\n self.sleep()\n\n def persist_index(self, df) -> None:\n df['timestamp'] = df['timestamp'].apply(lambda x: to_pd_timestamp(x))\n df['list_date'] = df['list_date'].apply(lambda x: to_pd_timestamp(x))\n df['id'] = df['code'].apply(lambda code: f'index_cn_{code}')\n df['entity_id'] = df['id']\n df['exchange'] = 'cn'\n df['entity_type'] = 'index'\n\n df = df.dropna(axis=0, how='any')\n df = df.drop_duplicates(subset='id', keep='last')\n\n df_to_db(df=df, data_schema=Index, provider=self.provider, force_update=False)\n\n\n__all__ = ['ChinaIndexListSpider']\n\nif __name__ == '__main__':\n spider = ChinaIndexListSpider(provider='exchange')\n spider.run()\n" ]
[ [ "pandas.to_datetime" ], [ "pandas.concat", "pandas.DataFrame", "pandas.read_html" ] ]
[ { "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": [ "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": [], "tensorflow": [] } ]
TUM-AIMED/hyfed
[ "06e0ea66a8bf88ecaf09ebc0ff20cdd850d81b7f" ]
[ "hyfed-compensator/hyfed_compensator/project/hyfed_compensator_project.py" ]
[ "\"\"\"\n The main class to obtain the compensation parameters from the clients, aggregate them,\n and share the aggregation results with the server\n\n Copyright 2021 Reza NasiriGerdeh. 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\nfrom hyfed_compensator.util.hyfed_parameters import Parameter, AuthenticationParameter, SyncParameter, ConnectionParameter, MonitoringParameter\nfrom hyfed_compensator.util.status import OperationStatus\nfrom hyfed_compensator.util.endpoint import EndPoint\nfrom hyfed_compensator.util.utils import aggregate\nfrom hyfed_compensator.util.monitoring import Timer, Counter\n\nimport pickle\nimport numpy as np\nimport time\nimport hashlib\nimport requests\nfrom datetime import datetime\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass HyFedCompensatorProject:\n \"\"\"\n Provide main functions to communicate with the clients and server,\n and to aggregate the compensation parameters from the clients\n \"\"\"\n\n def __init__(self, project_id_hash, client_count):\n \"\"\" Initialize the compensator project using the hash of the project ID and the number of clients \"\"\"\n\n # for compensator to know whether it has received compensation parameters from all clients\n self.client_count = client_count\n\n # hash of the project ID, which should be the same for all clients\n self.project_id_hash = project_id_hash\n\n # authentication parameters from the clients\n self.client_token_hashes = list()\n self.client_username_hashes = list()\n\n # sync parameters from the clients\n self.client_steps = list()\n self.client_comm_rounds = list()\n\n # compensation parameters (noise values) from the clients\n self.client_compensation_parameters = list()\n\n # data type parameters from clients\n self.client_data_type_parameters = list()\n\n # clients tell compensator where to send the aggregated noise values\n self.server_urls = list()\n\n # aggregated parameters have the same parameter names as the local model parameters of the clients\n self.aggregated_compensation_parameters = dict()\n\n # to tell the server whether the aggregation of noise values have been successful\n self.operation_status = OperationStatus.DONE\n\n # monitoring timers\n self.computation_timer = Timer(name='Computation')\n self.network_send_timer = Timer(name='Network Send')\n\n # counter to track the traffic client -> compensator (in terms of bytes)\n self.client_compensator_traffic = Counter(\"client->compensator\")\n\n self.upload_parameters_timeout = 600\n\n # used for garbage collection purposes\n self.last_updated_date = datetime.now().timestamp()\n\n def add_client_parameters(self, request):\n \"\"\" Append client's authentication, sync, connection, and compensation parameters to the corresponding lists \"\"\"\n\n try:\n # new communication round starts for compensator if the parameters from the first client is received\n if len(self.client_compensation_parameters) == 0:\n self.computation_timer.new_round()\n self.network_send_timer.new_round()\n\n # add traffic size to client -> compensator traffic counter\n traffic_size = int(request.headers['Content-Length'])\n self.client_compensator_traffic.increment(traffic_size)\n logger.debug(f'Project {self.project_id_hash}: {traffic_size} bytes added to client -> compensator traffic.')\n\n self.computation_timer.start()\n\n # extract client parameters from the request body\n request_body = pickle.loads(request.body)\n\n authentication_parameters = request_body[Parameter.AUTHENTICATION]\n sync_parameters = request_body[Parameter.SYNCHRONIZATION]\n compensation_parameters = request_body[Parameter.COMPENSATION]\n connection_parameters = request_body[Parameter.CONNECTION]\n data_type_parameters = request_body[Parameter.DATA_TYPE]\n\n # authentication parameters\n hash_username = authentication_parameters[AuthenticationParameter.HASH_USERNAME]\n hash_token = authentication_parameters[AuthenticationParameter.HASH_TOKEN]\n\n # sync parameters\n step = sync_parameters[SyncParameter.PROJECT_STEP]\n comm_round = sync_parameters[SyncParameter.COMM_ROUND]\n\n # connection parameter\n server_url = connection_parameters[ConnectionParameter.SERVER_URL]\n\n # add the parameters to the lists\n self.client_username_hashes.append(hash_username)\n self.client_token_hashes.append(hash_token)\n self.client_steps.append(step)\n self.client_comm_rounds.append(comm_round)\n self.server_urls.append(server_url)\n self.client_compensation_parameters.append(compensation_parameters)\n self.client_data_type_parameters.append(data_type_parameters)\n\n self.computation_timer.stop()\n\n logger.debug(f'Project {self.project_id_hash}: Client parameters added!')\n\n except Exception as add_parameter_exp:\n logger.error(f'Project {self.project_id_hash}: Adding client parameters was failed!')\n logger.error(f'Project {self.project_id_hash}: The exception is: {add_parameter_exp}')\n self.computation_timer.stop()\n self.set_operation_status_failed()\n\n def aggregate_client_parameters(self):\n \"\"\" Aggregate client parameters including the compensation parameters from all clients \"\"\"\n\n try:\n self.computation_timer.start()\n\n logger.debug(f\"Project {self.project_id_hash}: Aggregating client parameters ...\")\n\n # make sure all clients are in the same step and communication round\n if not self.is_client_sync_ok():\n logger.error(f'Project {self.project_id_hash}: The step/comm_round of the clients are different!')\n self.computation_timer.stop()\n self.set_operation_status_failed()\n return\n\n # ensure all clients are coordinated by the same server\n if not self.is_server_url_same():\n logger.error(f'Project {self.project_id_hash}: Server URL is different for the clients!')\n self.computation_timer.stop()\n self.set_operation_status_failed()\n return\n\n # make sure compensator parameter names are the same across the clients\n if not self.is_client_compensation_parameters_ok():\n logger.error(f'Project {self.project_id_hash}: Compensation parameter names are different across clients!')\n self.computation_timer.stop()\n self.set_operation_status_failed()\n return\n\n # aggregate the compensation parameters\n for parameter_name in self.client_compensation_parameters[0].keys():\n compensation_values = self.compensation_parameter_to_list(parameter_name)\n parameter_data_type = self.client_data_type_parameters[0][parameter_name]\n aggregated_compensation_value = aggregate(compensation_values, parameter_data_type)\n self.aggregated_compensation_parameters[parameter_name] = -aggregated_compensation_value\n\n self.computation_timer.stop()\n\n except Exception as aggregate_exp:\n logger.error(f'Project {self.project_id_hash}: Aggregating the compensation parameters was failed!')\n logger.error(f'Project {self.project_id_hash}: The exception is: {aggregate_exp}')\n self.computation_timer.stop()\n self.set_operation_status_failed()\n\n def send_to_server(self):\n \"\"\" Send aggregated authentication, sync, monitoring, and compensation parameters to the server \"\"\"\n\n # create and serialize request body\n parameters_serialized = self.prepare_server_parameters()\n\n max_tries = 10\n for _ in range(max_tries):\n try:\n\n logger.debug(f\"Project {self.project_id_hash}: Sending the aggregated parameters to the server ...\")\n\n self.network_send_timer.start()\n response = requests.post(url=f'{self.server_urls[0]}/{EndPoint.MODEL_COMPENSATION}',\n data=parameters_serialized,\n timeout=self.upload_parameters_timeout)\n\n if response.status_code == 200:\n logger.debug(f\"Project {self.project_id_hash}: Sending done!\")\n self.network_send_timer.stop()\n return\n\n logger.error(f\"Project {self.project_id_hash}: Sending failed, got {response.status_code} status code from the server!\")\n self.network_send_timer.stop()\n\n time.sleep(30)\n continue\n except Exception as send_server_exp:\n logger.error(f\"Project {self.project_id_hash}: Sending failed!\")\n logger.error(f'Project {self.project_id_hash}: The exception is: {send_server_exp}')\n self.network_send_timer.stop()\n time.sleep(30)\n\n def aggregate_and_send(self):\n \"\"\" First aggregate, and then, send aggregated parameters to the server \"\"\"\n\n # aggregate client parameters including compensation parameters\n self.aggregate_client_parameters()\n\n # send the aggregated parameters to the server\n self.send_to_server()\n\n # empty the lists/dictionaries for the next round\n self.client_token_hashes = list()\n self.client_username_hashes = list()\n self.client_steps = list()\n self.client_comm_rounds = list()\n self.client_compensation_parameters = list()\n self.client_data_type_parameters = list()\n self.server_urls = list()\n self.aggregated_compensation_parameters = dict()\n\n # ########## setter/getter functions\n def set_operation_status_done(self):\n \"\"\" If current operation is still in progress (not failed), then set it to Done \"\"\"\n\n if self.operation_status == OperationStatus.IN_PROGRESS:\n self.operation_status = OperationStatus.DONE\n\n def set_operation_status_in_progress(self):\n \"\"\" If previous operation is done (not failed), then set current operation status to In Progress \"\"\"\n\n if self.operation_status == OperationStatus.DONE:\n self.operation_status = OperationStatus.IN_PROGRESS\n\n def set_operation_status_failed(self):\n \"\"\" Regardless of the current status, set the operation status to Failed \"\"\"\n\n logger.error(\"Operation failed!\")\n self.operation_status = OperationStatus.FAILED\n\n def set_last_updated_date(self):\n self.last_updated_date = datetime.now().timestamp()\n\n def is_operation_failed(self):\n return self.operation_status == OperationStatus.FAILED\n\n def get_last_updated_date(self):\n return self.last_updated_date\n\n # ########## Helper functions\n def is_client_sync_ok(self):\n \"\"\" Ensure the project step and communication round of all clients is the same \"\"\"\n\n try:\n logger.debug(f\"Project {self.project_id_hash}: checking synchronization status of the clients ...\")\n\n return (np.all(np.array(self.client_steps) == self.client_steps[0]) and\n np.all(np.array(self.client_comm_rounds) == self.client_comm_rounds[0]))\n\n except Exception as sync_exp:\n logger.error(f'Project {self.project_id_hash}: Checking sync status of the clients was failed')\n logger.error(f'Project {self.project_id_hash}: The exception is: {sync_exp}')\n return False\n\n def is_server_url_same(self):\n \"\"\" Ensure the the server urls from all clients are the same \"\"\"\n\n try:\n\n logger.debug(f\"Project {self.project_id_hash}: Checking whether clients are coordinated by the same server ...\")\n\n return np.all(np.array(self.server_urls) == self.server_urls[0])\n\n except Exception as server_url_exp:\n logger.error(f'Project {self.project_id_hash}: Checking server urls was failed!')\n logger.error(f'Project {self.project_id_hash}: The exception is: {server_url_exp}')\n return False\n\n def is_client_compensation_parameters_ok(self):\n \"\"\" Make sure the names of the compensation parameters are consistent across clients \"\"\"\n try:\n logger.debug(f\"Project {self.project_id_hash}: checking whether compensation parameter names are consistent across all clients ...\")\n client1_compensation_parameter_names = self.client_compensation_parameters[0].keys()\n for client_parameters in self.client_compensation_parameters:\n\n if client_parameters.keys() != client1_compensation_parameter_names:\n return False\n\n return True\n except Exception as compensation_param_exp:\n logger.error(f'Project {self.project_id_hash}: Checking compensation parameter names was failed!')\n logger.error(f'Project {self.project_id_hash}: The exception is: {compensation_param_exp}')\n return False\n\n def is_client_data_type_parameters_ok(self):\n \"\"\" Make sure the names of the data type parameters are consistent across clients \"\"\"\n try:\n logger.debug(f\"Project {self.project_id_hash}: checking whether data type parameter names are consistent across all clients ...\")\n client1_data_type_parameter_names = self.client_data_type_parameters[0].keys()\n for client_parameters in self.client_data_type_parameters:\n if client_parameters.keys() != client1_data_type_parameter_names:\n return False\n\n return True\n except Exception as compensation_param_exp:\n logger.error(f'Project {self.project_id_hash}: Checking data type parameter names was failed!')\n logger.error(f'Project {self.project_id_hash}: The exception is: {compensation_param_exp}')\n return False\n\n def should_aggregate_and_send(self):\n \"\"\" Check whether compensation parameters from all clients received \"\"\"\n\n return len(self.client_username_hashes) == self.client_count\n\n def compensation_parameter_to_list(self, parameter_name):\n \"\"\"\n Extract the compensation parameter of the clients specified with parameter_name as a list\n \"\"\"\n\n compensation_parameter_list = []\n try:\n for compensation_parameter in self.client_compensation_parameters:\n compensation_parameter_list.append(compensation_parameter[parameter_name])\n except Exception as convert_exp:\n logger.error(f'Project {self.project_id_hash}: Converting compensation parameters to list was failed!')\n logger.error(f'Project {self.project_id_hash}: The exception is: {convert_exp}')\n self.set_operation_status_failed()\n\n return compensation_parameter_list\n\n def prepare_server_parameters(self):\n \"\"\" Prepare the parameters shared with the server \"\"\"\n\n try:\n self.computation_timer.start()\n\n # initialize authentication parameters\n authentication_parameters = dict()\n\n hash_username_hashes = hashlib.sha256(''.join(sorted(self.client_username_hashes)).encode('utf-8')).hexdigest()\n hash_token_hashes = hashlib.sha256(''.join(sorted(self.client_token_hashes)).encode('utf-8')).hexdigest()\n\n authentication_parameters[AuthenticationParameter.HASH_PROJECT_ID] = self.project_id_hash\n authentication_parameters[AuthenticationParameter.HASH_USERNAME_HASHES] = hash_username_hashes\n authentication_parameters[AuthenticationParameter.HASH_TOKEN_HASHES] = hash_token_hashes\n\n # initialize synchronization parameters\n sync_parameters = dict()\n sync_parameters[SyncParameter.PROJECT_STEP] = self.client_steps[0]\n sync_parameters[SyncParameter.COMM_ROUND] = self.client_comm_rounds[0]\n sync_parameters[SyncParameter.OPERATION_STATUS] = self.operation_status\n\n monitoring_parameters = dict()\n monitoring_parameters[MonitoringParameter.COMPUTATION_TIME] = self.computation_timer.get_total_duration()\n monitoring_parameters[MonitoringParameter.NETWORK_SEND_TIME] = self.network_send_timer.get_total_duration()\n monitoring_parameters[MonitoringParameter.CLIENT_COMPENSATOR_TRAFFIC] = self.client_compensator_traffic.total_count\n\n # server parameters in json\n server_parameters_json = {Parameter.AUTHENTICATION: authentication_parameters,\n Parameter.SYNCHRONIZATION: sync_parameters,\n Parameter.MONITORING: monitoring_parameters,\n Parameter.COMPENSATION: self.aggregated_compensation_parameters\n }\n server_parameters_serialized = pickle.dumps(server_parameters_json)\n\n self.computation_timer.stop()\n\n return server_parameters_serialized\n\n except Exception as prepare_exp:\n logger.error(f'Project {self.project_id_hash}: Preparing server parameters was failed!')\n logger.error(f'Project {self.project_id_hash}: The exception is: {prepare_exp}')\n self.computation_timer.stop()\n self.set_operation_status_failed()\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
muzi2045/second_TANET.pytorch
[ "3e10c93075a76684871fe0f188819c7b282671fd" ]
[ "second/core/non_max_suppression/nms_cpu.py" ]
[ "import math\r\nfrom pathlib import Path\r\nimport numba\r\nimport numpy as np\r\nfrom spconv.spconv_utils import (\r\n non_max_suppression_cpu, rotate_non_max_suppression_cpu)\r\nfrom second.core import box_np_ops\r\nfrom second.core.non_max_suppression.nms_gpu import rotate_iou_gpu\r\n\r\n\r\ndef nms_cc(dets, thresh):\r\n scores = dets[:, 4]\r\n order = scores.argsort()[::-1].astype(np.int32) # highest->lowest\r\n return non_max_suppression_cpu(dets, order, thresh, 1.0)\r\n\r\n\r\ndef rotate_nms_cc(dets, thresh):\r\n scores = dets[:, 5]\r\n order = scores.argsort()[::-1].astype(np.int32) # highest->lowest\r\n dets_corners = box_np_ops.center_to_corner_box2d(dets[:, :2], dets[:, 2:4],\r\n dets[:, 4])\r\n\r\n dets_standup = box_np_ops.corner_to_standup_nd(dets_corners)\r\n\r\n standup_iou = box_np_ops.iou_jit(dets_standup, dets_standup, eps=0.0)\r\n # print(dets_corners.shape, order.shape, standup_iou.shape)\r\n return rotate_non_max_suppression_cpu(dets_corners, order, standup_iou,\r\n thresh)\r\n\r\[email protected](nopython=True)\r\ndef nms_jit(dets, thresh, eps=0.0):\r\n x1 = dets[:, 0]\r\n y1 = dets[:, 1]\r\n x2 = dets[:, 2]\r\n y2 = dets[:, 3]\r\n scores = dets[:, 4]\r\n areas = (x2 - x1 + eps) * (y2 - y1 + eps)\r\n order = scores.argsort()[::-1].astype(np.int32) # highest->lowest\r\n ndets = dets.shape[0]\r\n suppressed = np.zeros((ndets), dtype=np.int32)\r\n keep = []\r\n for _i in range(ndets):\r\n i = order[_i] # start with highest score box\r\n if suppressed[\r\n i] == 1: # if any box have enough iou with this, remove it\r\n continue\r\n keep.append(i)\r\n for _j in range(_i + 1, ndets):\r\n j = order[_j]\r\n if suppressed[j] == 1:\r\n continue\r\n # calculate iou between i and j box\r\n w = max(min(x2[i], x2[j]) - max(x1[i], x1[j]) + eps, 0.0)\r\n h = max(min(y2[i], y2[j]) - max(y1[i], y1[j]) + eps, 0.0)\r\n inter = w * h\r\n ovr = inter / (areas[i] + areas[j] - inter)\r\n # ovr = inter / areas[j]\r\n if ovr >= thresh:\r\n suppressed[j] = 1\r\n return keep\r\n\r\n\r\[email protected]('float32[:, :], float32, float32, float32, uint32', nopython=True)\r\ndef soft_nms_jit(boxes, sigma=0.5, Nt=0.3, threshold=0.001, method=0):\r\n N = boxes.shape[0]\r\n pos = 0\r\n maxscore = 0\r\n maxpos = 0\r\n for i in range(N):\r\n maxscore = boxes[i, 4]\r\n maxpos = i\r\n\r\n tx1 = boxes[i, 0]\r\n ty1 = boxes[i, 1]\r\n tx2 = boxes[i, 2]\r\n ty2 = boxes[i, 3]\r\n ts = boxes[i, 4]\r\n pos = i + 1\r\n # get max box\r\n while pos < N:\r\n if maxscore < boxes[pos, 4]:\r\n maxscore = boxes[pos, 4]\r\n maxpos = pos\r\n pos = pos + 1\r\n\r\n # add max box as a detection\r\n boxes[i, 0] = boxes[maxpos, 0]\r\n boxes[i, 1] = boxes[maxpos, 1]\r\n boxes[i, 2] = boxes[maxpos, 2]\r\n boxes[i, 3] = boxes[maxpos, 3]\r\n boxes[i, 4] = boxes[maxpos, 4]\r\n\r\n # swap ith box with position of max box\r\n boxes[maxpos, 0] = tx1\r\n boxes[maxpos, 1] = ty1\r\n boxes[maxpos, 2] = tx2\r\n boxes[maxpos, 3] = ty2\r\n boxes[maxpos, 4] = ts\r\n\r\n tx1 = boxes[i, 0]\r\n ty1 = boxes[i, 1]\r\n tx2 = boxes[i, 2]\r\n ty2 = boxes[i, 3]\r\n ts = boxes[i, 4]\r\n\r\n pos = i + 1\r\n # NMS iterations, note that N changes if detection boxes fall below threshold\r\n while pos < N:\r\n x1 = boxes[pos, 0]\r\n y1 = boxes[pos, 1]\r\n x2 = boxes[pos, 2]\r\n y2 = boxes[pos, 3]\r\n s = boxes[pos, 4]\r\n\r\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\r\n iw = (min(tx2, x2) - max(tx1, x1) + 1)\r\n if iw > 0:\r\n ih = (min(ty2, y2) - max(ty1, y1) + 1)\r\n if ih > 0:\r\n ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area -\r\n iw * ih)\r\n ov = iw * ih / ua #iou between max box and detection box\r\n\r\n if method == 1: # linear\r\n if ov > Nt:\r\n weight = 1 - ov\r\n else:\r\n weight = 1\r\n elif method == 2: # gaussian\r\n weight = np.exp(-(ov * ov) / sigma)\r\n else: # original NMS\r\n if ov > Nt:\r\n weight = 0\r\n else:\r\n weight = 1\r\n\r\n boxes[pos, 4] = weight * boxes[pos, 4]\r\n\r\n # if box score falls below threshold, discard the box by swapping with last box\r\n # update N\r\n if boxes[pos, 4] < threshold:\r\n boxes[pos, 0] = boxes[N - 1, 0]\r\n boxes[pos, 1] = boxes[N - 1, 1]\r\n boxes[pos, 2] = boxes[N - 1, 2]\r\n boxes[pos, 3] = boxes[N - 1, 3]\r\n boxes[pos, 4] = boxes[N - 1, 4]\r\n N = N - 1\r\n pos = pos - 1\r\n\r\n pos = pos + 1\r\n\r\n keep = [i for i in range(N)]\r\n return keep\r\n\r\n" ]
[ [ "numpy.exp", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MuhammadSYahyaS/cs-flow
[ "bef320ae7b2063f1dce41fb2f2225228cd43a589" ]
[ "train.py" ]
[ "import numpy as np\nimport torch\nfrom sklearn.metrics import roc_auc_score\nfrom tqdm import tqdm\nimport config as c\nfrom model import get_cs_flow_model, save_model, FeatureExtractor, nf_forward\nfrom utils import *\n\n\ndef train(train_loader, test_loader):\n model = get_cs_flow_model()\n optimizer = torch.optim.Adam(model.parameters(), lr=c.lr_init, eps=1e-04, weight_decay=1e-5)\n model.to(c.device)\n if not c.pre_extracted:\n fe = FeatureExtractor()\n fe.eval()\n fe.to(c.device)\n for param in fe.parameters():\n param.requires_grad = False\n\n z_obs = Score_Observer('AUROC')\n\n for epoch in range(c.meta_epochs):\n # train some epochs\n model.train()\n if c.verbose:\n print(F'\\nTrain epoch {epoch}')\n for sub_epoch in range(c.sub_epochs):\n train_loss = list()\n for i, data in enumerate(tqdm(train_loader, disable=c.hide_tqdm_bar)):\n optimizer.zero_grad()\n\n inputs, labels = preprocess_batch(data) # move to device and reshape\n if not c.pre_extracted:\n inputs = fe(inputs)\n\n z, jac = nf_forward(model, inputs)\n\n loss = get_loss(z, jac)\n train_loss.append(t2np(loss))\n\n loss.backward()\n norm = torch.nn.utils.clip_grad_norm_(model.parameters(), c.max_grad_norm)\n optimizer.step()\n\n mean_train_loss = np.mean(train_loss)\n if c.verbose and epoch == 0 and sub_epoch % 4 == 0:\n print('Epoch: {:d}.{:d} \\t train loss: {:.4f}'.format(epoch, sub_epoch, mean_train_loss))\n\n # evaluate\n model.eval()\n if c.verbose:\n print('\\nCompute loss and scores on test set:')\n test_loss = list()\n test_z = list()\n test_labels = list()\n\n with torch.no_grad():\n for i, data in enumerate(tqdm(test_loader, disable=c.hide_tqdm_bar)):\n inputs, labels = preprocess_batch(data)\n if not c.pre_extracted:\n inputs = fe(inputs)\n\n z, jac = nf_forward(model, inputs)\n loss = get_loss(z, jac)\n\n z_concat = t2np(concat_maps(z))\n score = np.mean(z_concat ** 2, axis=(1, 2))\n test_z.append(score)\n test_loss.append(t2np(loss))\n test_labels.append(t2np(labels))\n\n test_loss = np.mean(np.array(test_loss))\n if c.verbose:\n print('Epoch: {:d} \\t test_loss: {:.4f}'.format(epoch, test_loss))\n\n test_labels = np.concatenate(test_labels)\n is_anomaly = np.array([0 if l == 0 else 1 for l in test_labels])\n\n anomaly_score = np.concatenate(test_z, axis=0)\n z_obs.update(roc_auc_score(is_anomaly, anomaly_score), epoch,\n print_score=c.verbose or epoch == c.meta_epochs - 1)\n\n if c.save_model:\n model.to('cpu')\n save_model(model, c.modelname)\n\n return z_obs.max_score, z_obs.last, z_obs.min_loss_score\n" ]
[ [ "sklearn.metrics.roc_auc_score", "numpy.concatenate", "torch.no_grad", "numpy.mean", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sungheeyun/optmlstat
[ "11d529c915bf27976da9157471a6dbf7df34d205" ]
[ "optmlstat/test/test_basic_functions.py" ]
[ "import unittest\nfrom logging import Logger, getLogger\n\nfrom numpy import ndarray, power, allclose\nfrom numpy.random import randn\nfrom freq_used.logging_utils import set_logging_basic_config\n\nfrom optmlstat.functions.function_base import FunctionBase\nfrom optmlstat.functions.example_functions import get_sum_of_square_function, get_sum_function\n\n\nlogger: Logger = getLogger()\n\n\nclass TestBasicFunctions(unittest.TestCase):\n num_inputs: int = 30\n num_data_points: int = 100\n x_array_2d: ndarray\n\n @classmethod\n def setUpClass(cls) -> None:\n set_logging_basic_config(__file__)\n cls.x_array_2d = randn(cls.num_data_points, cls.num_inputs)\n\n def test_sum_of_squares_function(self):\n y_array_1d: ndarray = TestBasicFunctions._get_y_array_1d(\n get_sum_of_square_function(TestBasicFunctions.num_inputs)\n )\n true_y_array_1d: ndarray = power(TestBasicFunctions.x_array_2d, 2.0).sum(axis=1)\n\n logger.info(y_array_1d.shape)\n logger.info(true_y_array_1d.shape)\n logger.info(allclose(y_array_1d, true_y_array_1d))\n\n self.assertTrue(allclose(y_array_1d, true_y_array_1d))\n\n def test_sum_function(self):\n y_array_1d: ndarray = TestBasicFunctions._get_y_array_1d(get_sum_function(TestBasicFunctions.num_inputs))\n true_y_array_1d: ndarray = power(TestBasicFunctions.x_array_2d, 1.0).sum(axis=1)\n\n logger.info(y_array_1d.shape)\n logger.info(true_y_array_1d.shape)\n logger.info(allclose(y_array_1d, true_y_array_1d))\n\n self.assertTrue(allclose(y_array_1d, true_y_array_1d))\n\n @classmethod\n def _get_y_array_1d(cls, function: FunctionBase) -> ndarray:\n return function.get_y_values_2d(cls.x_array_2d).ravel()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.random.randn", "numpy.allclose", "numpy.power" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mmderakhshani/ML-From-Scratch
[ "86ccc5273e0182b66c5d93c428f75dad61d8ced3" ]
[ "mlfromscratch/unsupervised_learning/gaussian_mixture_model.py" ]
[ "from __future__ import division, print_function\nimport sys\nimport os\nimport math\nimport random\nfrom sklearn import datasets\nimport numpy as np\n\n# Import helper functions\nfrom mlfromscratch.utils.data_manipulation import normalize\nfrom mlfromscratch.utils.data_operation import euclidean_distance, calculate_covariance_matrix\nfrom mlfromscratch.unsupervised_learning import PCA\nfrom mlfromscratch.utils import Plot\n\n\nclass GaussianMixtureModel():\n \"\"\"A probabilistic clustering method for determining groupings among data samples.\n\n Parameters:\n -----------\n k: int\n The number of clusters the algorithm will form.\n max_iterations: int\n The number of iterations the algorithm will run for if it does\n not converge before that. \n tolerance: float\n If the difference of the results from one iteration to the next is\n smaller than this value we will say that the algorithm has converged.\n \"\"\"\n def __init__(self, k=2, max_iterations=2000, tolerance=1e-8):\n self.k = k\n self.parameters = []\n self.max_iterations = max_iterations\n self.tolerance = tolerance\n self.responsibilities = []\n self.sample_assignments = None\n self.responsibility = None\n\n # Initialize gaussian randomly\n def _init_random_gaussians(self, X):\n n_samples = np.shape(X)[0]\n self.priors = (1 / self.k) * np.ones(self.k)\n for i in range(self.k):\n params = {}\n params[\"mean\"] = X[np.random.choice(range(n_samples))]\n params[\"cov\"] = calculate_covariance_matrix(X)\n self.parameters.append(params)\n\n # Likelihood\n def multivariate_gaussian(self, X, params):\n n_features = np.shape(X)[1]\n mean = params[\"mean\"]\n covar = params[\"cov\"]\n determinant = np.linalg.det(covar)\n likelihoods = np.zeros(np.shape(X)[0])\n for i, sample in enumerate(X):\n d = n_features # dimension\n coeff = (1.0 / (math.pow((2.0 * math.pi), d / 2)\n * math.sqrt(determinant)))\n exponent = math.exp(-0.5 * (sample - mean).T.dot(np.linalg.pinv(covar)).dot((sample - mean)))\n likelihoods[i] = coeff * exponent\n\n return likelihoods\n\n # Calculate the likelihood over all samples\n def _get_likelihoods(self, X):\n n_samples = np.shape(X)[0]\n likelihoods = np.zeros((n_samples, self.k))\n for i in range(self.k):\n likelihoods[\n :, i] = self.multivariate_gaussian(\n X, self.parameters[i])\n return likelihoods\n\n # Calculate the responsibility\n def _expectation(self, X):\n # Calculate probabilities of X belonging to the different clusters\n weighted_likelihoods = self._get_likelihoods(X) * self.priors\n sum_likelihoods = np.expand_dims(\n np.sum(weighted_likelihoods, axis=1), axis=1)\n # Determine responsibility as P(X|y)*P(y)/P(X)\n self.responsibility = weighted_likelihoods / sum_likelihoods\n # Assign samples to cluster that has largest probability\n self.sample_assignments = self.responsibility.argmax(axis=1)\n # Save value for convergence check\n self.responsibilities.append(np.max(self.responsibility, axis=1))\n\n # Update the parameters and priors\n def _maximization(self, X):\n # Iterate through clusters and recalculate mean and covariance\n for i in range(self.k):\n resp = np.expand_dims(self.responsibility[:, i], axis=1)\n mean = (resp * X).sum(axis=0) / resp.sum()\n covariance = (X - mean).T.dot((X - mean) * resp) / resp.sum()\n self.parameters[i][\"mean\"], self.parameters[\n i][\"cov\"] = mean, covariance\n\n # Update weights\n n_samples = np.shape(X)[0]\n self.priors = self.responsibility.sum(axis=0) / n_samples\n\n # Covergence if || likehood - last_likelihood || < tolerance\n def _converged(self, X):\n if len(self.responsibilities) < 2:\n return False\n diff = np.linalg.norm(\n self.responsibilities[-1] - self.responsibilities[-2])\n # print (\"Likelihood update: %s (tol: %s)\" % (diff, self.tolerance))\n return diff <= self.tolerance\n\n # Run GMM and return the cluster indices\n def predict(self, X):\n # Initialize the gaussians randomly\n self._init_random_gaussians(X)\n\n # Run EM until convergence or for max iterations\n for _ in range(self.max_iterations):\n self._expectation(X) # E-step\n self._maximization(X) # M-step\n\n # Check convergence\n if self._converged(X):\n break\n\n # Make new assignments and return them\n self._expectation(X)\n return self.sample_assignments\n\ndef main():\n # Load the dataset\n X, y = datasets.make_blobs()\n\n # Cluster the data\n clf = GaussianMixtureModel(k=3)\n y_pred = clf.predict(X)\n\n p = MatplotlibWrapper()\n p.plot_in_2d(X, y_pred, title=\"GMM Clustering\")\n p.plot_in_2d(X, y, title=\"Actual Clustering\")\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.expand_dims", "numpy.linalg.norm", "numpy.ones", "numpy.linalg.det", "numpy.max", "numpy.linalg.pinv", "numpy.shape", "numpy.zeros", "numpy.sum", "sklearn.datasets.make_blobs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EEEGUI/Mapillary-vistas-semseg
[ "d07a107fd08a7536f09f25e426a6f15033cbb609" ]
[ "ptsemseg/loader/mapillary_vistas_loader.py" ]
[ "import os\nimport json\nimport torch\nimport numpy as np\n\nfrom torch.utils import data\nfrom PIL import Image\n\nfrom ptsemseg.utils import recursive_glob\nfrom ptsemseg.augmentations import Compose, RandomHorizontallyFlip, RandomRotate\n\nclass mapillaryVistasLoader(data.Dataset):\n def __init__(\n self,\n root,\n split=\"training\",\n img_size=(1025, 2049),\n is_transform=True,\n augmentations=None,\n test_mode=False,\n ):\n self.root = root\n self.split = split\n self.is_transform = is_transform\n self.augmentations = augmentations\n self.n_classes = 9\n\n self.img_size = img_size if isinstance(img_size, tuple) else (img_size, img_size)\n self.mean = np.array([80.5423, 91.3162, 81.4312])\n self.files = {}\n\n if not test_mode:\n self.images_base = os.path.join(self.root, self.split, \"images\")\n self.annotations_base = os.path.join(self.root, self.split, \"labels\")\n self.files[split] = recursive_glob(rootdir=self.images_base, suffix=\".jpg\")\n if not self.files[split]:\n raise Exception(\"No files for split=[%s] found in %s\" % (split, self.images_base))\n\n print(\"Found %d %s images\" % (len(self.files[split]), split))\n self.class_names, self.class_ids, self.class_colors, self.class_major_ids = self.parse_config()\n\n self.ignore_id = 250\n\n\n\n def parse_config(self):\n with open(os.path.join(self.root, \"config.json\")) as config_file:\n config = json.load(config_file)\n\n labels = config[\"labels\"]\n\n class_names = []\n class_ids = []\n class_colors = []\n class_major_ids = []\n\n for label_id, label in enumerate(labels):\n class_names.append(label[\"readable\"])\n class_ids.append(label_id)\n class_colors.append(label[\"color\"])\n class_major_ids.append(label['majorclass'])\n print(\"There are {} labels in the config file\".format(len(set(class_major_ids))))\n return class_names, class_ids, class_colors, class_major_ids\n\n def __len__(self):\n \"\"\"__len__\"\"\"\n return len(self.files[self.split])\n\n def __getitem__(self, index):\n \"\"\"__getitem__\n :param index:\n \"\"\"\n img_path = self.files[self.split][index].rstrip()\n lbl_path = os.path.join(\n self.annotations_base, os.path.basename(img_path).replace(\".jpg\", \".png\")\n )\n\n img = Image.open(img_path)\n lbl = Image.open(lbl_path)\n if self.augmentations is not None:\n img, lbl = self.augmentations(img, lbl)\n if self.is_transform:\n img, lbl = self.transform(img, lbl)\n return img, lbl\n\n def transform(self, img, lbl):\n if self.img_size == (\"same\", \"same\"):\n pass\n else:\n img = img.resize(\n (self.img_size[1], self.img_size[0]), resample=Image.LANCZOS\n ) # uint8 with RGB mode\n lbl = lbl.resize((self.img_size[1], self.img_size[0]))\n img = np.array(img).astype(np.float64) / 255.0\n img = torch.from_numpy(img.transpose(2, 0, 1)).float() # From HWC to CHW\n #\n # lbl = torch.from_numpy(np.array(lbl)).long()\n # lbl[lbl == 65] = self.ignore_id\n #\n lbl = torch.from_numpy(np.array(lbl)).long()\n lbl[lbl == self.ignore_id] = 65\n lbl = self.encode_segmap(lbl)\n lbl[lbl == 0] = self.ignore_id\n return img, lbl\n\n def decode_segmap(self, temp):\n class_major_colors = [[0, 0, 0],\n [70, 70, 70],\n [180, 165, 180],\n [128, 64, 64],\n [220, 20, 60],\n [255, 255, 255],\n [70, 130, 180],\n [250, 170, 30],\n [0, 0, 142]]\n r = temp.copy()\n g = temp.copy()\n b = temp.copy()\n for l in range(0, len(class_major_colors)):\n r[temp == l] = class_major_colors[l][0]\n g[temp == l] = class_major_colors[l][1]\n b[temp == l] = class_major_colors[l][2]\n\n rgb = np.zeros((temp.shape[0], temp.shape[1], 3))\n # rgb[:, :, 0] = r / 255.0\n # rgb[:, :, 1] = g / 255.0\n # rgb[:, :, 2] = b / 255.0\n rgb[:, :, 0] = r\n rgb[:, :, 1] = g\n rgb[:, :, 2] = b\n return rgb\n\n def encode_segmap(self, mask):\n # Put all void classes to zero\n for id in self.class_ids:\n mask[mask == id] = self.class_major_ids[id]+100\n\n mask = mask - 100\n return mask\n\n\nif __name__ == \"__main__\":\n augment = Compose([RandomHorizontallyFlip(0.5), RandomRotate(6)])\n\n local_path = \"/home/lin/Documents/dataset/mapillary\"\n dst = mapillaryVistasLoader(\n local_path, split='validation', img_size=(512, 1024), is_transform=True, augmentations=None\n )\n bs = 1\n trainloader = data.DataLoader(dst, batch_size=bs, num_workers=4, shuffle=True)\n for i, data_samples in enumerate(trainloader):\n x = dst.decode_segmap(data_samples[1][0].numpy())\n x = Image.fromarray(np.uint8(x))\n x.show()\n\n" ]
[ [ "numpy.uint8", "numpy.array", "torch.utils.data.DataLoader", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vinay-swamy/gMVP
[ "62202baa0769dfe0e47c230e78dffa42fb1280f1" ]
[ "trainer/trainer.py" ]
[ "import time\nimport json\nimport argparse\nimport os\nimport sys\nimport logging\nimport shutil\nfrom datetime import datetime\nimport glob\nimport random\n\nfrom scipy.stats import mannwhitneyu\nfrom scipy.stats import spearmanr\n\nimport numpy as np\n\nfrom sklearn.metrics import roc_auc_score, precision_recall_curve, auc\n\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\n#from optimization import create_optimizer\n\nfrom model_attention import ModelAttention\n\nfrom dataset import build_dataset\nfrom loss import compute_loss\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\ntf.config.threading.set_intra_op_parallelism_threads(60)\ntf.config.threading.set_inter_op_parallelism_threads(60)\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nlogging_formatter = logging.Formatter(\n '%(asctime)s - %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\nch = logging.StreamHandler(sys.stdout)\nch.setFormatter(logging_formatter)\nlogger.addHandler(ch)\n\n\nclass LearningRate(tf.keras.optimizers.schedules.LearningRateSchedule):\n def __init__(self, base_lr, end_learning_rate, warmup_steps, decay_steps):\n super(LearningRate, self).__init__()\n self.base_lr = base_lr\n self.warmup_steps = warmup_steps\n self.decay_steps = decay_steps\n if decay_steps == 0:\n self.poly_decay_fn = lambda x: self.base_lr\n else:\n self.poly_decay_fn = tf.keras.optimizers.schedules.PolynomialDecay(\n base_lr,\n decay_steps,\n end_learning_rate=end_learning_rate,\n power=1.0)\n\n def __call__(self, step):\n lr = tf.cond(\n step < self.warmup_steps, lambda: self.base_lr * tf.cast(\n step + 1, tf.float32) / tf.cast(self.warmup_steps, tf.float32),\n lambda: self.poly_decay_fn(step - self.warmup_steps))\n #if step % 100 == 0:\n # tf.print('learning_rate', step, lr)\n\n return lr\n\n\nclass TestMetric(object):\n def __init__(self):\n self._targets = tf.zeros((0, ), tf.int32)\n self._preds = tf.zeros((0, ), tf.float32)\n\n def reset_states(self):\n self._targets = tf.zeros((0, ), tf.int32)\n self._preds = tf.zeros((0, ), tf.float32)\n\n def update_state(self, targets, preds):\n self._targets = tf.concat(\n [self._targets, tf.cast(targets, tf.int32)], axis=-1)\n self._preds = tf.concat(\n [self._preds, tf.cast(preds, tf.float32)], axis=-1)\n\n def result_auROC(self):\n try:\n auROC = roc_auc_score(self._targets.numpy(), self._preds.numpy())\n return auROC\n except:\n return 0.0\n\n def result_auPR(self):\n try:\n precision, recall, _ = precision_recall_curve(\n self._targets.numpy(), self._preds.numpy())\n auPR = auc(recall, precision)\n return auPR\n except:\n return 0.0\n\n def result_pvalue(self):\n all_pred = self._preds.numpy()\n all_label = self._targets.numpy()\n mtest = mannwhitneyu(all_pred[all_label == 1],\n all_pred[all_label == 0],\n alternative='two-sided')\n pvalue = mtest.pvalue\n return pvalue\n\n def result_total(self):\n res = self._targets.numpy()\n return res.shape[0]\n\n def result_neg(self):\n res = self._targets.numpy()\n return res.shape[0] - np.sum(res)\n\n def result_pos(self):\n res = self._targets.numpy()\n return np.sum(res)\n\n def result_corr(self):\n try:\n all_pred = self._preds.numpy()\n all_label = self._targets.numpy()\n corr, pvalue = spearmanr(all_pred, all_label)\n return corr, pvalue\n except:\n return 0.0\n\n def result_max(self):\n try:\n all_pred = self._preds.numpy()\n return np.max(all_pred)\n except:\n return 0.0\n\n\ndef train_single_gpu(config, args):\n #setup logger\n str_t = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n train_dir = f'./res/{str_t}'\n config['train']['train_dir'] = train_dir\n os.makedirs(train_dir)\n os.makedirs(train_dir + '/result')\n os.makedirs(train_dir + '/model')\n\n fh = logging.FileHandler(f'{train_dir}/train.log')\n fh.setFormatter(logging_formatter)\n logger.addHandler(fh)\n\n logger.info(json.dumps(config, indent=4))\n\n #train and validate files\n batch_size = config['train']['batch_size']\n input_config = config['input']\n input_base_dir = input_config['base_dir']\n all_files = glob.glob(input_base_dir + '/' + input_config['train'][:-1] +\n args.random + '*tfrec')\n #all_files = glob.glob('../dataset/tf/f_v1_w64_2021_v2' + '/' +\n # input_config['train'][:-1] + args.random + '*tfrec')\n random.seed(2020)\n random.shuffle(all_files)\n train_files, validate_files = [], []\n for i in range(10):\n if i == args.cv:\n validate_files.append(all_files[i])\n else:\n train_files.append(all_files[i])\n\n print(train_files)\n print(validate_files)\n\n asd = glob.glob(input_base_dir + '/' + 'ASD' + '.tfrec')\n ndd = glob.glob(input_base_dir + '/' + 'NDD' + '.tfrec')\n control = glob.glob(input_base_dir + '/' + 'Control' + '.tfrec')\n brca2 = glob.glob(input_base_dir + '/' + 'BRCA2' + '.tfrec')\n pparg = glob.glob(input_base_dir + '/' + 'PPARG' + '.tfrec')\n #train_files += pparg\n\n train_dataset = build_dataset(train_files, batch_size)\n validate_dataset = build_dataset(validate_files, batch_size)\n\n #model\n model_type = config['train']['model_type']\n if model_type == 'attention':\n model = ModelAttention(config['model'])\n else:\n raise ValueError(f'model type {model_type} does not exist.')\n #learning rate\n init_learning_rate = config['train']['learning_rate']\n end_learning_rate = config['train']['end_learning_rate']\n '''\n warmup_epochs = config['train']['warmup_epochs']\n decay_epochs = config['train']['decay_epochs']\n\n training_samples = 0\n for inputs in train_dataset:\n training_samples += inputs[0].shape[0]\n logger.info(f'training_samples= {training_samples}')\n\n batches_each_epoch = int(training_samples / batch_size)\n warmup_steps = batches_each_epoch * warmup_epochs\n decay_steps = batches_each_epoch * decay_epochs\n '''\n\n warmup_steps, decay_steps = config['train']['warmup_steps'], config[\n 'train']['decay_steps']\n\n learning_rate = LearningRate(init_learning_rate,\n end_learning_rate=end_learning_rate,\n warmup_steps=warmup_steps,\n decay_steps=decay_steps)\n\n #training algorithm\n opt = config['train'].get('opt', 'adam')\n if opt == 'adam':\n optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)\n #optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3)\n elif opt == 'adamw':\n weight_decay_rate = config['train']['weight_decay_rate']\n optimizer = tfa.optimizers.AdamW(\n weight_decay=weight_decay_rate,\n learning_rate=learning_rate,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-8,\n )\n '''\n optimizer = create_optimizer(init_learning_rate,\n decay_steps + warmup_steps,\n warmup_steps,\n end_lr=end_learning_rate,\n optimizer_type='adamw')\n '''\n\n else:\n raise NotImplementedError(f\"opt {opt} not NotImplementedError\")\n\n #metrics\n metric_train_loss = tf.keras.metrics.Mean(name='train_loss')\n metric_test_loss = tf.keras.metrics.Mean(name='test_loss')\n metric_test = TestMetric()\n\n #summary\n train_log_dir = f'{train_dir}/summary/train'\n train_summary_writer = tf.summary.create_file_writer(train_log_dir)\n\n def _update_histogram_summary():\n with train_summary_writer.as_default():\n for var in model.trainable_variables:\n if 'kernel:' in var.name or 'gamma:' in var.name or 'beta:' in var.name:\n tf.summary.histogram(var.name,\n var,\n step=optimizer.iterations)\n\n def _update_gradient_norm_summary(var, grad):\n with train_summary_writer.as_default():\n for v, g in zip(var, grad):\n if 'kernel:' in v.name or 'gamma:' in v.name or 'beta:' in v.name:\n tf.summary.scalar(f'gradient_norm/{v.name}',\n tf.norm(g, ord='euclidean'),\n step=optimizer.iterations)\n\n @tf.function(input_signature=[validate_dataset.element_spec])\n def test_step(sample):\n var, ref_aa, alt_aa, feature, label, padding_mask = sample\n\n logit = model((ref_aa, alt_aa, feature), False, padding_mask)\n\n loss = compute_loss(label, logit)\n\n pred = model.predict_from_logit(logit)\n\n return var, label, pred, loss\n\n def _save_res(var_id, target, pred, name, epoch):\n with open(f'{train_dir}/result/epoch_{epoch}_{name}.score', 'w') as f:\n f.write('var\\ttarget\\tScore\\n')\n for a, c, d in zip(var_id, target, pred):\n f.write('{}\\t{:d}\\t{:f}\\n'.format(a.numpy().decode('utf-8'),\n int(c), d))\n return True\n\n def test(test_dataset,\n data_name,\n epoch,\n auc=False,\n pvalue=False,\n corr=False):\n metric_test_loss.reset_states()\n metric_test.reset_states()\n\n all_pred, all_label, all_var = [], [], []\n\n for step, sample in enumerate(test_dataset):\n var, label, pred, loss = test_step(sample)\n metric_test.update_state(label, pred)\n metric_test_loss.update_state(loss)\n\n all_pred.extend(list(pred))\n all_label.extend(list(label))\n all_var.extend(list(var))\n\n all_var = np.array(all_var)\n all_label = np.array(all_label)\n all_pred = np.array(all_pred)\n\n _save_res(all_var, all_label, all_pred, data_name, epoch)\n\n if auc:\n logger.info(\n f'{data_name} pos= {metric_test.result_pos()} neg= {metric_test.result_neg()} loss= {metric_test_loss.result()} auPR= {metric_test.result_auPR()} auROC= {metric_test.result_auROC()} max= {metric_test.result_max()}'\n )\n if pvalue:\n logger.info(\n f'{data_name} pos= {metric_test.result_pos()} neg= {metric_test.result_neg()} loss= {metric_test_loss.result()} pvalue= {metric_test.result_pvalue()}'\n )\n\n if corr:\n corr, pvalue = metric_test.result_corr()\n logger.info(\n f'{data_name} pos= {metric_test.result_total()} corr= {corr} pvalue= {pvalue} max= {metric_test.result_max()}'\n )\n\n return metric_test_loss.result()\n\n @tf.function(input_signature=[train_dataset.element_spec])\n def train_step(sample):\n var, ref_aa, alt_aa, feature, label, padding_mask = sample\n with tf.GradientTape() as tape:\n logit = model((ref_aa, alt_aa, feature), True, padding_mask)\n loss = compute_loss(label, logit)\n\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n metric_train_loss.update_state(loss)\n #if optimizer.iterations % 512 == 0:\n # _update_gradient_norm_summary(model.trainable_variables, gradients)\n\n return loss\n\n EPOCHS = 512\n watch_loss = 10000.0\n watch_epoch = -1\n patience_epochs = 5\n for epoch in range(EPOCHS):\n start = time.time()\n\n for step, samples in enumerate(train_dataset):\n loss = train_step(samples)\n #tf.print(\n # f'lr= {learning_rate(global_step)} wd={weight_decay(global_step)}'\n #)\n\n #model summary\n if optimizer.iterations == 1:\n model.summary(print_fn=logger.info)\n\n #logging kernel weights\n #if (optimizer.iterations + 1) % 512 == 0:\n # _update_histogram_summary()\n\n logger.info(f'Epoch {epoch} Loss {metric_train_loss.result():.4f}')\n metric_train_loss.reset_states()\n\n model.save_weights(f'{train_dir}/model/epoch-{epoch}.h5')\n\n #validate and test\n validate_loss = test(validate_dataset,\n 'validate',\n epoch,\n pvalue=False,\n auc=True,\n corr=False)\n if validate_loss < watch_loss:\n watch_loss = validate_loss\n watch_epoch = epoch\n\n #denovo\n if epoch - watch_epoch == patience_epochs:\n logger.info(f'best_epoch {watch_epoch} min_loss= {watch_loss}')\n break\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--config', type=str, required=True)\n parser.add_argument('--cv', type=int, default=0)\n parser.add_argument('--random', type=str, default='0')\n args = parser.parse_args()\n\n with open(args.config) as f:\n config = json.load(f)\n\n train_single_gpu(config, args)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.norm", "tensorflow.config.threading.set_intra_op_parallelism_threads", "tensorflow.keras.optimizers.schedules.PolynomialDecay", "tensorflow.summary.histogram", "tensorflow.zeros", "sklearn.metrics.auc", "scipy.stats.spearmanr", "tensorflow.cast", "numpy.max", "scipy.stats.mannwhitneyu", "tensorflow.function", "tensorflow.keras.optimizers.Adam", "tensorflow.GradientTape", "tensorflow.config.threading.set_inter_op_parallelism_threads", "numpy.array", "numpy.sum", "tensorflow.keras.metrics.Mean", "tensorflow.summary.create_file_writer" ] ]
[ { "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": [] } ]
v1259397/cosmic-gnuradio
[ "64c149520ac6a7d44179c3f4a38f38add45dd5dc" ]
[ "gnuradio-3.7.13.4/gr-analog/python/analog/qa_fastnoise.py" ]
[ "#!/usr/bin/env python\n#\n# Copyright 2007,2010,2012 Free Software Foundation, Inc.\n#\n# This file is part of GNU Radio\n#\n# GNU Radio 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, or (at your option)\n# any later version.\n#\n# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to\n# the Free Software Foundation, Inc., 51 Franklin Street,\n# Boston, MA 02110-1301, USA.\n#\n\nfrom gnuradio import gr, gr_unittest, analog, blocks\nimport numpy\n\n\nclass test_fastnoise_source(gr_unittest.TestCase):\n\n def setUp (self):\n\n self.num = 2**22\n self.num_items = 10**6\n self.default_args = {\"samples\": self.num, \"seed\": 43, \"ampl\": 1}\n\n def tearDown (self):\n pass\n\n def run_test_real(self, form):\n \"\"\" Run test case with float input/output\n \"\"\"\n tb = gr.top_block()\n src = analog.fastnoise_source_f(type=form, **self.default_args)\n head = blocks.head(nitems=self.num_items, sizeof_stream_item=gr.sizeof_float)\n sink = blocks.vector_sink_f()\n tb.connect(src, head, sink)\n tb.run()\n return numpy.array(sink.data())\n\n def run_test_complex(self, form):\n \"\"\" Run test case with complex input/output\n \"\"\"\n tb = gr.top_block()\n src = analog.fastnoise_source_c(type=form, **self.default_args)\n head = blocks.head(nitems=self.num_items, sizeof_stream_item=gr.sizeof_gr_complex)\n sink = blocks.vector_sink_c()\n tb.connect(src, head, sink)\n tb.run()\n return numpy.array(sink.data())\n\n def test_001_real_uniform_moments(self):\n\n data = self.run_test_real(analog.GR_UNIFORM)\n\n self.assertAlmostEqual(min(data), -1, places=4)\n self.assertAlmostEqual(max(data), 1, places=4)\n\n # mean, variance\n self.assertAlmostEqual(data.mean(), 0, places=2)\n self.assertAlmostEqual(data.var(), (1-(-1))**2./12, places=3)\n\n def test_001_real_gaussian_moments(self):\n data = self.run_test_real(analog.GR_GAUSSIAN)\n\n # mean, variance\n self.assertAlmostEqual(data.mean(), 0, places=2)\n self.assertAlmostEqual(data.var(), 1, places=2)\n\n def test_001_real_laplacian_moments(self):\n data = self.run_test_real(analog.GR_LAPLACIAN)\n\n # mean, variance\n self.assertAlmostEqual(data.mean(), 0, places=2)\n self.assertAlmostEqual(data.var(), 2, places=2)\n\n def test_001_complex_uniform_moments(self):\n data = self.run_test_complex(analog.GR_UNIFORM)\n\n # mean, variance\n self.assertAlmostEqual(data.real.mean(), 0, places=2)\n self.assertAlmostEqual(data.real.var(), 0.5*(1-(-1))**2./12, places=3)\n\n self.assertAlmostEqual(data.imag.mean(), 0, places=2)\n self.assertAlmostEqual(data.imag.var(), 0.5*(1-(-1))**2./12, places=3)\n\n def test_001_complex_gaussian_moments(self):\n data = self.run_test_complex(analog.GR_GAUSSIAN)\n\n # mean, variance\n self.assertAlmostEqual(data.real.mean(), 0, places=2)\n self.assertAlmostEqual(data.real.var(), 0.5, places=2)\n\n self.assertAlmostEqual(data.imag.mean(), 0, places=2)\n self.assertAlmostEqual(data.imag.var(), 0.5, places=2)\n\n def test_002_real_uniform_reproducibility(self):\n data1 = self.run_test_real(analog.GR_UNIFORM)\n data2 = self.run_test_real(analog.GR_UNIFORM)\n\n # It's pseudoramdo thus must be equal\n self.assertTrue(numpy.array_equal(data1, data2))\n\n def test_002_real_gaussian_reproducibility(self):\n data1 = self.run_test_real(analog.GR_GAUSSIAN)\n data2 = self.run_test_real(analog.GR_GAUSSIAN)\n\n self.assertTrue(numpy.array_equal(data1, data2))\n\n def test_003_real_uniform_pool(self):\n src = analog.fastnoise_source_f(type=analog.GR_UNIFORM, **self.default_args)\n src2 = analog.fastnoise_source_f(type=analog.GR_UNIFORM, **self.default_args)\n self.assertTrue(numpy.array_equal(numpy.array(src.samples()), numpy.array(src2.samples())))\n def test_003_real_gaussian_pool(self):\n src = analog.fastnoise_source_f(type=analog.GR_GAUSSIAN, **self.default_args)\n src2 = analog.fastnoise_source_f(type=analog.GR_GAUSSIAN, **self.default_args)\n self.assertTrue(numpy.array_equal(numpy.array(src.samples()), numpy.array(src2.samples())))\n def test_003_cmplx_gaussian_pool(self):\n src = analog.fastnoise_source_c(type=analog.GR_GAUSSIAN, **self.default_args)\n src2 = analog.fastnoise_source_c(type=analog.GR_GAUSSIAN, **self.default_args)\n self.assertTrue(numpy.array_equal(numpy.array(src.samples()), numpy.array(src2.samples())))\n def test_003_cmplx_uniform_pool(self):\n src = analog.fastnoise_source_c(type=analog.GR_UNIFORM, **self.default_args)\n src2 = analog.fastnoise_source_c(type=analog.GR_UNIFORM, **self.default_args)\n self.assertTrue(numpy.array_equal(numpy.array(src.samples()), numpy.array(src2.samples())))\n def test_003_real_laplacian_pool(self):\n src = analog.fastnoise_source_f(type=analog.GR_LAPLACIAN, **self.default_args)\n src2 = analog.fastnoise_source_f(type=analog.GR_LAPLACIAN, **self.default_args)\n self.assertTrue(numpy.array_equal(numpy.array(src.samples()), numpy.array(src2.samples())))\nif __name__ == '__main__':\n gr_unittest.run(test_fastnoise_source, \"test_fastnoise_source.xml\")\n" ]
[ [ "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Saiprasad16/transform
[ "774458bf0c296f8275fedf3ace303427654dace7" ]
[ "tensorflow_transform/schema_inference.py" ]
[ "# Copyright 2017 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\"\"\"Logic associated with schema inference and propagation.\n\nThis module contains functionality to set the schema assciated with a Tensor,\nand to infer the schema for a tensor, including any information that has been\nset. This module will also contain any schema propagation logic, i.e. deducing\nthe schema of a tensor from its parents in the graph.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nfrom typing import Callable, Dict, Mapping, Optional, Tuple\n\n# GOOGLE-INITIALIZATION\n\nimport tensorflow as tf\nfrom tensorflow_transform import common\nfrom tensorflow_transform import common_types\nfrom tensorflow_transform import graph_context\nfrom tensorflow_transform import tf2_utils\nfrom tensorflow_transform import tf_utils\nfrom tensorflow_transform.saved import saved_transform_io_v2\nfrom tensorflow_transform.tf_metadata import schema_utils\n\nfrom google.protobuf import any_pb2\n# pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.framework import ops\n# pylint: enable=g-direct-tensorflow-import\nfrom tensorflow_metadata.proto.v0 import schema_pb2\n\n\ndef _feature_spec_from_batched_tensors(tensors):\n \"\"\"Infer a feature spec from a dict of tensors.\n\n Args:\n tensors: A dict whose keys are strings and values are `Tensor`,\n `SparseTensor`, or `RaggedTensor`s.\n\n Returns:\n A feature spec inferred from the types and shapes of the tensors.\n\n Raises:\n ValueError: If the feature spec cannot be inferred.\n TypeError: If any of the values of `tensors` are not a `Tensor`,\n `SparseTensor`, or `RaggedTensor`.\n \"\"\"\n feature_spec = {}\n for name, tensor in tensors.items():\n if tensor.dtype not in (tf.string, tf.int64, tf.float32):\n raise ValueError('Feature {} ({}) had invalid dtype {} for feature spec'\n .format(name, tensor, tensor.dtype))\n if isinstance(tensor, tf.SparseTensor):\n shape = tensor.get_shape()\n if shape.ndims > 2:\n feature_spec[name] = tf.io.SparseFeature(\n index_key=[\n '{}$sparse_indices_{}'.format(name, idx)\n for idx in range(shape.ndims - 1)\n ],\n value_key='{}$sparse_values'.format(name),\n dtype=tensor.dtype,\n size=shape[1:],\n already_sorted=True)\n else:\n feature_spec[name] = tf.io.VarLenFeature(tensor.dtype)\n elif isinstance(tensor, tf.Tensor):\n shape = tensor.get_shape()\n if shape.ndims in [None, 0]:\n raise ValueError(\n 'Feature {} ({}) had invalid shape {} for FixedLenFeature: must '\n 'have rank at least 1'.format(name, tensor, shape))\n if any(dim is None for dim in shape.as_list()[1:]):\n raise ValueError(\n 'Feature {} ({}) had invalid shape {} for FixedLenFeature: apart '\n 'from the batch dimension, all dimensions must have known size'\n .format(name, tensor, shape))\n feature_spec[name] = tf.io.FixedLenFeature(shape.as_list()[1:],\n tensor.dtype)\n elif isinstance(tensor, tf.RaggedTensor):\n tf.compat.v1.logging.warn(\n 'Feature %s was a RaggedTensor. A Schema will be generated but the '\n 'Schema cannot be used with a coder (e.g. to materialize output '\n 'data) or to generated a feature spec.', name)\n # Arbitrarily select VarLenFeature.\n feature_spec[name] = tf.io.VarLenFeature(tensor.dtype)\n else:\n raise TypeError(\n 'Expected a Tensor, SparseTensor, or RaggedTensor got {} of type {} '\n 'for feature {}'\n .format(tensor, type(tensor), name))\n\n return feature_spec\n\n\ndef infer_feature_schema(features, graph, session=None):\n \"\"\"Given a dict of tensors, creates a `Schema`.\n\n Infers a schema, in the format of a tf.Transform `Schema`, for the given\n dictionary of tensors.\n\n If there is an override specified, we override the inferred schema for the\n given feature's tensor. An override has the meaning that we should set\n is_categorical=True. If session is not provided then we just set\n is_categorical=True, and if the session is provided then was also compute\n values of the tensors representing the min and max values and set them in the\n schema.\n\n If annotations have been specified, they are added to the output schema.\n\n Args:\n features: A dict mapping column names to `Tensor` or `SparseTensor`s. The\n `Tensor` or `SparseTensor`s should have a 0'th dimension which is\n interpreted as the batch dimension.\n graph: A `tf.Graph` used to determine schema overrides.\n session: (optional) A `tf.Session` used to compute schema overrides. If\n None, schema overrides will not be computed.\n\n Returns:\n A `Schema` proto.\n \"\"\"\n tensor_ranges = _get_tensor_ranges(graph)\n if session is None:\n tensor_ranges = {hashable: (None, None) for hashable in tensor_ranges}\n tensor_annotations = {}\n global_annotations = []\n else:\n tensor_ranges = session.run(tensor_ranges)\n tensor_annotations, global_annotations = _get_schema_annotations(\n graph, session)\n modified_tensor_ranges = {}\n feature_annotations = {}\n for name, tensor in features.items():\n if isinstance(tensor, tf.SparseTensor):\n values = tensor.values\n elif isinstance(tensor, tf.RaggedTensor):\n values = tensor.flat_values\n else:\n values = tensor\n hashable_values = tf_utils.hashable_tensor_or_op(values)\n if hashable_values in tensor_ranges:\n assert values.dtype == tf.int64\n modified_tensor_ranges[name] = tensor_ranges[hashable_values]\n # tensor_annotations is a defaultdict(list) so always returns a list.\n feature_annotations[name] = tensor_annotations.get(hashable_values, [])\n\n return _infer_feature_schema_common(features, modified_tensor_ranges,\n feature_annotations, global_annotations)\n\n\ndef infer_feature_schema_v2(features, concrete_metadata_fn,\n evaluate_schema_overrides):\n \"\"\"Given a dict of tensors, creates a `Schema`.\n\n Infers a schema, in the format of a tf.Transform `Schema`, for the given\n dictionary of tensors.\n\n If there is an override specified, we override the inferred schema for the\n given feature's tensor. An override has the meaning that we should set\n is_categorical=True. If evaluate_schema_overrides is False then we just set\n is_categorical=True, and if evaluate_schema_overrides is True then we also\n compute values of the tensors representing the min and max values and set them\n in the schema.\n\n If annotations have been specified, they are added to the output schema.\n\n Args:\n features: A dict mapping column names to `Tensor` or `SparseTensor`s. The\n `Tensor` or `SparseTensor`s should have a 0'th dimension which is\n interpreted as the batch dimension.\n concrete_metadata_fn: A `tf.ConcreteFunction` that returns a dictionary\n containing the deferred annotations added to the graph when invoked with\n any valid input.\n evaluate_schema_overrides: A Boolean used to compute schema overrides. If\n `False`, schema overrides will not be computed.\n\n Returns:\n A `Schema` proto.\n \"\"\"\n optimized_concrete_fn = saved_transform_io_v2.optimize_concrete_function(\n concrete_metadata_fn)\n metadata = collections.defaultdict(list, optimized_concrete_fn())\n\n if not evaluate_schema_overrides:\n tensor_ranges = {\n tensor.numpy().decode(): (None, None)\n for tensor in metadata[_TF_METADATA_TENSOR_COLLECTION]\n }\n tensor_annotations = {}\n global_annotations = []\n else:\n tensor_ranges = _get_tensor_ranges_v2(metadata)\n tensor_annotations, global_annotations = _get_schema_annotations_v2(\n metadata)\n return _infer_feature_schema_common(features, tensor_ranges,\n tensor_annotations, global_annotations)\n\n\ndef _infer_feature_schema_common(features, tensor_ranges, feature_annotations,\n global_annotations):\n \"\"\"Given a dict of tensors, creates a `Schema`.\n\n Args:\n features: A dict mapping column names to `Tensor` or `SparseTensor`s. The\n `Tensor` or `SparseTensor`s should have a 0'th dimension which is\n interpreted as the batch dimension.\n tensor_ranges: A dict mapping a tensor to a tuple containing its min and max\n value.\n feature_annotations: dictionary from feature name to list of any_pb2.Any\n protos to be added as an annotation for that feature in the schema.\n global_annotations: list of any_pb2.Any protos to be added at the global\n schema level.\n\n Returns:\n A `Schema` proto.\n \"\"\"\n domains = {}\n feature_tags = collections.defaultdict(list)\n for name, tensor in features.items():\n if isinstance(tensor, tf.RaggedTensor):\n # Add the 'ragged_tensor' tag which will cause coder and\n # schema_as_feature_spec to raise an error, as currently there is no\n # feature spec for ragged tensors.\n feature_tags[name].append(schema_utils.RAGGED_TENSOR_TAG)\n if name in tensor_ranges:\n min_value, max_value = tensor_ranges[name]\n domains[name] = schema_pb2.IntDomain(\n min=min_value, max=max_value, is_categorical=True)\n feature_spec = _feature_spec_from_batched_tensors(features)\n\n schema_proto = schema_utils.schema_from_feature_spec(feature_spec, domains)\n\n # Add the annotations to the schema.\n for annotation in global_annotations:\n schema_proto.annotation.extra_metadata.add().CopyFrom(annotation)\n # Build a map from logical feature names to Feature protos\n feature_protos_by_name = {}\n for feature in schema_proto.feature:\n feature_protos_by_name[feature.name] = feature\n for sparse_feature in schema_proto.sparse_feature:\n for index_feature in sparse_feature.index_feature:\n feature_protos_by_name.pop(index_feature.name)\n value_feature = feature_protos_by_name.pop(\n sparse_feature.value_feature.name)\n feature_protos_by_name[sparse_feature.name] = value_feature\n # Update annotations\n for feature_name, annotations in feature_annotations.items():\n feature_proto = feature_protos_by_name[feature_name]\n for annotation in annotations:\n feature_proto.annotation.extra_metadata.add().CopyFrom(annotation)\n for feature_name, tags in feature_tags.items():\n feature_proto = feature_protos_by_name[feature_name]\n for tag in tags:\n feature_proto.annotation.tag.append(tag)\n return schema_proto\n\n\n# Names of collections, which should all be the same length and contain tensors.\n# Each tensor in the first collection should have its min/max described by the\n# tensors in the other two collections.\n_TF_METADATA_TENSOR_COLLECTION = 'tft_schema_override_tensor'\n_TF_METADATA_TENSOR_MIN_COLLECTION = 'tft_schema_override_min'\n_TF_METADATA_TENSOR_MAX_COLLECTION = 'tft_schema_override_max'\n# Collections for adding to annotation.extra_metadata on the schema. Each\n# tensor in the first collection should have a proto type and proto message in\n# the other two collections\n_TF_METADATA_EXTRA_ANNOTATION = 'tft_schema_override_annotation_tensor'\n_TF_METADATA_EXTRA_ANNOTATION_TYPE_URL = 'tft_schema_override_annotation_type'\n_TF_METADATA_EXTRA_ANNOTATION_PROTO = 'tft_schema_override_annotation_proto'\n# Used to indicate that an annotation should be applied at the schema level.\n_TF_METADATA_EXTRA_ANNOTATION_GLOBAL = 'tft_schema_override_global_sentinel'\n\n\ndef set_tensor_schema_override(tensor, min_value, max_value):\n \"\"\"Override parts of the schema of a `Tensor`.\n\n Args:\n tensor: The `Tensor` whose range is being set. Must have dtype int64.\n min_value: A `Tensor` representing the min value of `tensor`.\n max_value: A `Tensor` representing the max value of `tensor`.\n\n Raises:\n ValueError: If any arguments are invalid.\n \"\"\"\n if not isinstance(tensor, tf.Tensor):\n raise ValueError('tensor {} was not a Tensor'.format(tensor))\n if tensor.dtype != tf.int64:\n raise ValueError(\n 'Range can only be set for feature of type tf.int64, got {}'.format(\n tensor.dtype))\n if not isinstance(min_value, tf.Tensor):\n raise ValueError('min_value {} was not a Tensor'.format(min_value))\n if not isinstance(max_value, tf.Tensor):\n raise ValueError('max_value {} was not a Tensor'.format(max_value))\n tf.compat.v1.add_to_collection(_TF_METADATA_TENSOR_COLLECTION, tensor)\n tf.compat.v1.add_to_collection(_TF_METADATA_TENSOR_MIN_COLLECTION, min_value)\n tf.compat.v1.add_to_collection(_TF_METADATA_TENSOR_MAX_COLLECTION, max_value)\n\n\ndef _get_tensor_ranges(graph):\n \"\"\"Lookup overrides for `Tensor`s or `SparseTensor`s.\"\"\"\n tensors = graph.get_collection(_TF_METADATA_TENSOR_COLLECTION)\n min_values = graph.get_collection(_TF_METADATA_TENSOR_MIN_COLLECTION)\n max_values = graph.get_collection(_TF_METADATA_TENSOR_MAX_COLLECTION)\n assert len(tensors) == len(min_values), '{} != {}'.format(tensors, min_values)\n assert len(tensors) == len(max_values), '{} != {}'.format(tensors, max_values)\n return dict(zip(map(tf_utils.hashable_tensor_or_op, tensors),\n zip(min_values, max_values)))\n\n\ndef _get_tensor_ranges_v2(metadata):\n \"\"\"Lookup overrides for `Tensor`s or `SparseTensor`s.\"\"\"\n tensors = metadata[_TF_METADATA_TENSOR_COLLECTION]\n min_values = metadata[_TF_METADATA_TENSOR_MIN_COLLECTION]\n max_values = metadata[_TF_METADATA_TENSOR_MAX_COLLECTION]\n assert len(tensors) == len(min_values), '{} != {}'.format(tensors, min_values)\n assert len(tensors) == len(max_values), '{} != {}'.format(tensors, max_values)\n return {\n tensor.numpy().decode(): (min_value.numpy(), max_value.numpy())\n for (tensor, min_value, max_value) in zip(tensors, min_values, max_values)\n }\n\n\ndef get_tensor_schema_override(\n tensor: common_types.TensorType) -> Tuple[tf.Tensor, tf.Tensor]:\n \"\"\"Lookup schema overrides for a `Tensor` or `SparseTensor`.\"\"\"\n if isinstance(tensor, tf.SparseTensor):\n tensor = tensor.values\n overrides = _get_tensor_ranges(tensor.graph)\n min_max = overrides.get(tf_utils.hashable_tensor_or_op(tensor), None)\n if min_max is None:\n raise ValueError('Requested tensor does not have recorded min/max values')\n return min_max\n\n\ndef annotate(type_url, proto_message, tensor=None):\n \"\"\"Adds a deferred annotation to the schema.\n\n Experimental: This API is subject to change.\n\n This function allows analyzers or end users to annotate the post-transform\n schema with additional information based on analyzer output. These annotations\n are stored in the annotation.extra_metadata field of the tf.metadata schema:\n https://github.com/tensorflow/metadata/blob/master/tensorflow_metadata/proto/v0/schema.proto#L193\n\n Args:\n type_url: A string or string `Tensor` containing the type url which uniquely\n identifies the type of the serialized proto message. See\n https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto#L151\n proto_message: A deferred string tensor containing the serialized proto to\n write to the feature schema.\n tensor: (optional) If provided, the annotation will be written to the\n Feature proto that is created for this tensor in the schema. If None,\n the annotation is assumed to be global. Note: if the tensor is not present\n in the output signature of `preprocessing_fn`, this will be a no-op.\n \"\"\"\n if tensor is None:\n tensor = tf.constant('unused', name=_TF_METADATA_EXTRA_ANNOTATION_GLOBAL)\n\n if not isinstance(tensor, (tf.Tensor, tf.SparseTensor)):\n raise ValueError('tensor {} was not a Tensor'.format(tensor))\n if not isinstance(proto_message, tf.Tensor):\n raise ValueError('proto_message {} was not a Tensor'.format(proto_message))\n\n # If the type_url is passed as a plain string, create a string tensor.\n if not isinstance(type_url, tf.Tensor):\n type_url = tf.constant(type_url, dtype=tf.string)\n # Note: The tensors, types, and messages are stored in separate collections\n # because SavedModel only supports primitive types in collections.\n tf.compat.v1.add_to_collection(_TF_METADATA_EXTRA_ANNOTATION, tensor)\n tf.compat.v1.add_to_collection(_TF_METADATA_EXTRA_ANNOTATION_TYPE_URL,\n type_url)\n tf.compat.v1.add_to_collection(_TF_METADATA_EXTRA_ANNOTATION_PROTO,\n proto_message)\n\n\ndef _get_schema_annotations(graph, session):\n \"\"\"Fetch extra_metadata annotations to be applied to the schema.\n\n Extracts any deferred annotations that have been added to the graph and\n evaluates them to obtain any_pb2.Any proto messages.\n\n Args:\n graph: A `tf.Graph` used to determine schema overrides.\n session: (optional) A `tf.Session` used to compute schema annotations. If\n None, schema annotations will not be computed.\n\n Returns:\n tensor_annotations: dictionary from tensor to list of any_pb2.Any protos to\n be added as an annotation for that tensor's feature in the schema.\n global_annotations: list of any_pb2.Any protos to be added at the global\n schema level.\n \"\"\"\n tensors = graph.get_collection(_TF_METADATA_EXTRA_ANNOTATION)\n type_urls = session.run(\n graph.get_collection(_TF_METADATA_EXTRA_ANNOTATION_TYPE_URL))\n proto_values = session.run(\n graph.get_collection(_TF_METADATA_EXTRA_ANNOTATION_PROTO))\n tensor_annotation_keys = []\n for tensor in tensors:\n # Entries meant for the global schema annotation will have names like\n # tft_schema_override_global_sentinel:0 or\n # transform/tft_schema_override_global_sentinel_1:0\n tensor_name = tensor.name.split('/')[-1]\n if tensor_name.startswith(_TF_METADATA_EXTRA_ANNOTATION_GLOBAL):\n tensor_annotation_keys.append(_TF_METADATA_EXTRA_ANNOTATION_GLOBAL)\n else:\n tensor_annotation_keys.append(tf_utils.hashable_tensor_or_op(tensor))\n return _get_schema_annotations_common(tensor_annotation_keys, type_urls,\n proto_values)\n\n\ndef _get_schema_annotations_v2(metadata):\n \"\"\"Fetch extra_metadata annotations to be applied to the schema.\n\n Extracts any deferred annotations that have been added to the graph and\n evaluates them to obtain any_pb2.Any proto messages.\n\n Args:\n metadata: A dictionary containing the deferred annotations added to the\n graph.\n\n Returns:\n tensor_annotations: dictionary from tensor to list of any_pb2.Any protos to\n be added as an annotation for that tensor's feature in the schema.\n global_annotations: list of any_pb2.Any protos to be added at the global\n schema level.\n \"\"\"\n type_urls = [\n type_url.numpy()\n for type_url in metadata[_TF_METADATA_EXTRA_ANNOTATION_TYPE_URL]\n ]\n proto_values = [\n proto_value.numpy()\n for proto_value in metadata[_TF_METADATA_EXTRA_ANNOTATION_PROTO]\n ]\n tensor_annotation_keys = [\n tensor.numpy().decode()\n for tensor in metadata[_TF_METADATA_EXTRA_ANNOTATION]\n ]\n return _get_schema_annotations_common(tensor_annotation_keys, type_urls,\n proto_values)\n\n\ndef _get_schema_annotations_common(tensor_annotation_keys, type_urls,\n proto_values):\n \"\"\"Fetch extra_metadata annotations to be applied to the schema.\n\n Args:\n tensor_annotation_keys: A list containing either\n `_TF_METADATA_EXTRA_ANNOTATION_GLOBAL` or a hashed tensor representation\n corresponding to each entry in `proto_values`. If an entry\n is`_TF_METADATA_EXTRA_ANNOTATION_GLOBAL`, the corresponding any_pb2.Any\n proto in `proto_values` is returned in `global_annotations`. Otherwise, it\n is returned in `feature_annotations`.\n type_urls: A list of type urls corresponding to the serialized protos in\n `proto_values`.\n proto_values: A list of serialized any_pb2.Any protos.\n\n Returns:\n A tuple of:\n tensor_annotations: dictionary from tensor to list of any_pb2.Any protos to\n be added as an annotation for that tensor's feature in the schema.\n global_annotations: list of any_pb2.Any protos to be added at the global\n schema level.\n \"\"\"\n tensor_annotations = collections.defaultdict(list)\n global_annotations = []\n if not common.IS_ANNOTATIONS_PB_AVAILABLE:\n return tensor_annotations, global_annotations\n assert len(tensor_annotation_keys) == len(type_urls) == len(proto_values)\n for (tensor_annotation_key, type_url,\n proto_value) in zip(tensor_annotation_keys, type_urls, proto_values):\n annotation = any_pb2.Any(type_url=type_url, value=proto_value)\n if (isinstance(_TF_METADATA_EXTRA_ANNOTATION_GLOBAL,\n type(tensor_annotation_key)) and\n tensor_annotation_key == _TF_METADATA_EXTRA_ANNOTATION_GLOBAL):\n global_annotations.append(annotation)\n else:\n tensor_annotations[tensor_annotation_key].append(annotation)\n return tensor_annotations, global_annotations\n\n\ndef _get_tensor_value_to_key_map(features_dict):\n \"\"\"Get reverse map from name of tensor values to key in `features_dict`.\"\"\"\n result = {}\n for key, tensor in features_dict.items():\n if isinstance(tensor, tf.SparseTensor):\n values = tensor.values\n elif isinstance(tensor, tf.RaggedTensor):\n values = tensor.flat_values\n else:\n values = tensor\n result[values.name] = key\n return result\n\n\ndef _get_schema_overrides(graph,\n tensor_name_to_key_map,\n tensor_collection_key,\n overrides_keys,\n default_tensor_name=None):\n \"\"\"Obtain schema overrides from graph collections.\n\n For every tensor in the `tensor_collection_key` collection, the corresponding\n feature name is in `tensor_name_to_key_map` and its schema overrides are in\n the graph collections defined by keys in `overrides_keys`.\n If a tensor does not exist in `tensor_name_to_key_map` but its name starts\n with `default_tensor_name` (if provided), the overrides are returned with this\n key.\n\n Args:\n graph: A `FuncGraph`.\n tensor_name_to_key_map: A dictionary from tensor name to output feature key.\n tensor_collection_key: Key for the graph collection that contains list of\n tensors to annotate.\n overrides_keys: A list of graph collection keys that contain schema\n overrides/annotations.\n default_tensor_name: (Optional) A String. If provided, use as feature key if\n a tensor in the graph collections is not in `tensor_name_to_key_map`.\n\n Returns:\n A dictionary from graph collection keys to lists of features and their\n schema overrides/annotations.\n\n \"\"\"\n tensors = graph.get_collection(tensor_collection_key)\n overrides_list = [graph.get_collection(k) for k in overrides_keys]\n\n result = collections.defaultdict(list)\n assert (len(tensors) == len(overrides_list[0]) and\n all(len(lst) == len(overrides_list[0]) for lst in overrides_list))\n for tensor, overrides_tuple in zip(tensors, zip(*overrides_list)):\n if tensor.name in tensor_name_to_key_map:\n result[tensor_collection_key].append(tensor_name_to_key_map[tensor.name])\n else:\n if default_tensor_name is None:\n continue\n tensor_name = tensor.name.split('/')[-1]\n if tensor.dtype == tf.string and tensor_name.startswith(\n default_tensor_name):\n result[tensor_collection_key].append(default_tensor_name)\n else:\n continue\n\n # If a feature name was added to the result list for tensor_collection_key,\n # add its annotations as well.\n assert len(overrides_keys) == len(overrides_tuple)\n for overrides_key, override in zip(overrides_keys, overrides_tuple):\n result[overrides_key].append(override)\n return result\n\n\ndef get_traced_metadata_fn(\n tensor_replacement_map: Optional[Dict[str, tf.Tensor]],\n preprocessing_fn: Callable[[Mapping[str, common_types.InputTensorType]],\n Mapping[str, common_types.InputTensorType]],\n structured_inputs: Mapping[str, common_types.InputTensorType],\n base_temp_dir: str, evaluate_schema_overrides: bool) -> function.Function:\n \"\"\"Get a tf.function that returns a dictionary of annotations.\n\n Annotations are added to graph collections keyed by graph tensor names when\n `preprocessing_fn` is being traced. The metadata fn defined by this method\n converts the graph tensor names to output feature keys.\n\n If `evaluate_schema_overrides` is True, tracing the `preprocessing_fn` will\n add overrides for feature ranges (min/max) and/or feature protos to the graph\n collection, if applicable. These overrides are returned when the function\n returned by this method is invoked.\n\n Args:\n tensor_replacement_map: A map from placeholder tensor names to their\n evaluated replacement tensors.\n preprocessing_fn: A user defined python function to be traced.\n structured_inputs: A dictionary of placeholder inputs to `preprocessing_fn`.\n base_temp_dir: Base path to write any dummy assets to during tracing.\n evaluate_schema_overrides: If `False`, the returned dictionary contains a\n single key `_TF_METADATA_TENSOR_COLLECTION` as all other annotations are\n deferred. Else, the returned dictionary contains several deferred\n annotations.\n\n Returns:\n A dictionary whose keys represent the types of annotations and the values\n are collections of feature keys/annotations.\n \"\"\"\n\n # Since this is a TFT-internal function with constant outputs, autograph will\n # not affect its behavior. It will only increase tracing time, if enabled.\n # Hence, trace with `autograph=False` here.\n @tf.function(input_signature=[], autograph=False)\n def metadata_fn():\n graph = ops.get_default_graph()\n inputs = tf2_utils.supply_missing_inputs(structured_inputs, batch_size=1)\n with graph_context.TFGraphContext(\n temp_dir=base_temp_dir, evaluated_replacements=tensor_replacement_map):\n transformed_features = preprocessing_fn(inputs)\n\n # Get a map from tensor value names to feature keys.\n reversed_features = _get_tensor_value_to_key_map(transformed_features)\n\n result = collections.defaultdict(list)\n if not evaluate_schema_overrides:\n schema_override_tensors = graph.get_collection(\n _TF_METADATA_TENSOR_COLLECTION)\n for tensor in schema_override_tensors:\n if tensor.name in reversed_features:\n result[_TF_METADATA_TENSOR_COLLECTION].append(\n reversed_features[tensor.name])\n else:\n # Obtain schema overrides for feature tensor ranges.\n result.update(\n _get_schema_overrides(graph, reversed_features,\n _TF_METADATA_TENSOR_COLLECTION, [\n _TF_METADATA_TENSOR_MIN_COLLECTION,\n _TF_METADATA_TENSOR_MAX_COLLECTION\n ]))\n # Obtain schema overrides for feature protos. If no feature tensor is in\n # the `_TF_METADATA_EXTRA_ANNOTATION` collection for a specified\n # annotation, `_TF_METADATA_EXTRA_ANNOTATION_GLOBAL` is used as the\n # feature name to indicate that this annotation should be added to the\n # global schema.\n result.update(\n _get_schema_overrides(graph, reversed_features,\n _TF_METADATA_EXTRA_ANNOTATION, [\n _TF_METADATA_EXTRA_ANNOTATION_TYPE_URL,\n _TF_METADATA_EXTRA_ANNOTATION_PROTO\n ], _TF_METADATA_EXTRA_ANNOTATION_GLOBAL))\n return result\n\n return metadata_fn\n" ]
[ [ "tensorflow.constant", "tensorflow.compat.v1.logging.warn", "tensorflow.io.VarLenFeature", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.compat.v1.add_to_collection", "tensorflow.function" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] } ]
ZzhKlaus/2018-SURF-Trajectory-Estimation
[ "71c62c816d1531f6806bfa9455fec9affe36496c" ]
[ "Data_Processing/BoxPlot_error.py" ]
[ "#By Zhenghang(Klaus) Zhong\n\n#Box Plot of error distribution\n\nfrom pandas import DataFrame\nfrom pandas import read_csv\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot\n# load results into a dataframe\nfilenames_128 = ['dis_diff_128.csv']\nfilenames_256 = ['dis_diff_256.csv']\nfilenames_512 = ['dis_diff_512.csv']\nresults = DataFrame()\n\nfor name in filenames_128:\n\tresults_128 = read_csv(name, header=0,usecols = [1])\n# describe all results, as 1 unit = 10cm, we want to transfer to meters, /10\nresults_128 = results_128.div(10, axis = 0)\n\nfor name in filenames_256:\n\tresults_256 = read_csv(name, header=0,usecols = [1])\n# describe all results\nresults_256 = results_256.div(10, axis = 0)\n\nfor name in filenames_512:\n\tresults_512 = read_csv(name, header=0,usecols = [1])\n# describe all results\nresults_512 = results_512.div(10, axis = 0)\n\nprint(results_128.describe())\nprint(results_256.describe())\nprint(results_512.describe())\n\n# box and whisker plot\ndf = pd.DataFrame(np.concatenate((results_128,results_512),axis = 1),\ncolumns=['128', '512'])\n\ndf.boxplot(sym='k',showmeans = True,showfliers = False,return_type='dict')\n#results_256.boxplot(sym='k',showmeans = True,whis = [0,8],showfliers = False,return_type='dict')\n\npyplot.xlabel('Hidden node')\npyplot.ylabel('Error (m)')\npyplot.show()" ]
[ [ "pandas.read_csv", "pandas.DataFrame", "numpy.concatenate", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
python3f/spectral_clustering
[ "bd5900dfa7ada69bd77080b905ef08ea62b420e9" ]
[ "main.py" ]
[ "from sklearn.cluster import KMeans\nfrom sklearn.neighbors import kneighbors_graph\nfrom scipy.spatial.distance import pdist, squareform\nfrom scipy.sparse.csgraph import laplacian\nimport numpy as np\n\n\n\"\"\"Args:\nX: input samples, array (num, dim)\nn_clusters: no. of clusters\nn_neighbours: neighborhood size\n\nReturns:\nY: labels for samples, array (num,)\n\"\"\"\ndef spectral_clustering(X, n_clusters=2, n_neighbors=10):\n n, d = X.shape\n A = kneighbors_graph(X, n_neighbors, mode='connectivity').toarray()\n L = laplacian(A, normed=True)\n w, v = np.linalg.eig(L)\n w, v = w.real, v.real\n i = np.argsort(w)\n w, v = w[i], v[:,i]\n Y = KMeans(n_clusters).fit_predict(v[:,:2])\n return Y\n" ]
[ [ "sklearn.cluster.KMeans", "numpy.linalg.eig", "sklearn.neighbors.kneighbors_graph", "scipy.sparse.csgraph.laplacian", "numpy.argsort" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
sinzlab/orbit_transfer
[ "812d89af5c7ab26d9ea26766a4250ae023bb20b8", "812d89af5c7ab26d9ea26766a4250ae023bb20b8" ]
[ "orbit_transfer/models/__init__.py", "orbit_transfer/dataset/mnist_c/run_generation.py" ]
[ "import torch\nimport numpy as np\nfrom torch.hub import load_state_dict_from_url\n\nfrom nnfabrik.utility.nn_helpers import load_state_dict\n\n\nfrom nntransfer.models.resnet import resnet_builder\nfrom nntransfer.models.utils import get_model_parameters\nfrom nntransfer.models.vgg import vgg_builder\nfrom nntransfer.models.lenet import lenet_builder\nfrom nntransfer.models.wrappers import *\n\nfrom ..configs.model import (\n ClassificationModel,\n)\nfrom .cnn import cnn_builder\nfrom .group_cnn import gcnn_builder\nfrom .learned_equiv import equiv_builder\nfrom .mlp import mlp_builder\nfrom .vit import vit_builder\n\n\ndef classification_model_builder(data_loader, seed: int, **config):\n config = ClassificationModel.from_dict(config)\n torch.manual_seed(seed)\n np.random.seed(seed)\n if \"vgg\" in config.type:\n model = vgg_builder(seed, config)\n from torchvision.models.vgg import model_urls\n elif \"resnet\" in config.type:\n model = resnet_builder(seed, config)\n from torchvision.models.resnet import model_urls\n elif \"lenet\" in config.type:\n model = lenet_builder(seed, config)\n elif \"mlp\" in config.type:\n model = mlp_builder(seed, config)\n elif \"vit\" in config.type:\n model = vit_builder(seed, config)\n elif \"gcnn\" in config.type:\n model = gcnn_builder(seed, config)\n elif \"cnn\" in config.type:\n model = cnn_builder(seed, config)\n elif \"equiv_transfer\" in config.type:\n model = equiv_builder(seed, config)\n else:\n raise Exception(\"Unknown type {}\".format(config.type))\n\n if config.pretrained:\n print(\"Downloading pretrained model:\", flush=True)\n url = (\n model_urls[config.type]\n if not config.pretrained_url\n else config.pretrained_url\n )\n state_dict = load_state_dict_from_url(url, progress=True)\n try:\n load_state_dict(model, state_dict)\n except:\n load_state_dict(model, state_dict[\"model_state_dict\"])\n\n print(\"Model with {} parameters.\".format(get_model_parameters(model)))\n if config.add_buffer:\n for n, p in model.named_parameters():\n if p.requires_grad:\n n = n.replace(\".\", \"__\")\n for b in config.add_buffer:\n if isinstance(b, str):\n model.register_buffer(\n f\"{n}_{b}\",\n p.detach().clone().zero_(),\n )\n else:\n k = b[1]\n b = b[0]\n model.register_buffer(\n f\"{n}_{b}\",\n torch.zeros(k, *p.data.shape),\n )\n if config.add_custom_buffer:\n for key, size in config.add_custom_buffer.items():\n model.register_buffer(\n key,\n torch.zeros(size),\n )\n # Add wrappers\n if config.get_intermediate_rep:\n model = IntermediateLayerGetter(\n model, return_layers=config.get_intermediate_rep, keep_output=True\n )\n if config.noise_adv_regression or config.noise_adv_classification:\n assert not config.self_attention\n model = NoiseAdvWrapper(\n model,\n input_size=model.fc.in_features\n if \"resnet\" in config.type\n else model.n_features,\n hidden_size=model.fc.in_features if \"resnet\" in config.type else 4096,\n classification=config.noise_adv_classification,\n num_noise_readout_layers=config.num_noise_readout_layers,\n sigmoid_output=config.noise_sigmoid_output,\n )\n return model\n", "import os\nimport numpy as np\nfrom . import generate_and_save\n\n\ndef main(dataset=\"FashionMNIST\"):\n for bias in [\n # \"clean\",\n # \"color\",\n # \"color_shuffle\",\n # \"translation\",\n # \"rotation\",\n # \"rotation_regression\",\n # \"noise\",\n # \"addition_regression\",\n # \"scale\",\n # \"addition_regression_noise\",\n \"translation_negative\",\n \"translation_positive\",\n ]:\n generate_and_save(\n bias, base_path=\"./data/image_classification/torchvision/\", dataset=dataset\n )\n train_tensor = np.load(\n os.path.join(\n f\"./data/image_classification/torchvision/{dataset}-Transfer\",\n f\"{bias}_train_source.npy\",\n )\n )\n mean = np.mean(train_tensor, axis=(0, 2, 3))\n std = np.std(train_tensor, axis=(0, 2, 3))\n print(f\"Saved {dataset}-{bias} with mean {mean} and std {std}\")\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.manual_seed", "torch.hub.load_state_dict_from_url", "numpy.random.seed", "torch.zeros" ], [ "numpy.std", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
inamori/DeepLearningImplementations
[ "8bbd3c5a4a7d24b2c098ba47cfd45fe2c152771d", "8bbd3c5a4a7d24b2c098ba47cfd45fe2c152771d", "8bbd3c5a4a7d24b2c098ba47cfd45fe2c152771d" ]
[ "GAN_tf/src/model/flags.py", "Colorful/src/utils/general_utils.py", "WGAN-GP/src/model/train_wgan_GP.py" ]
[ "\nimport tensorflow as tf\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef define_flags():\n\n ############\n # Run mode\n ############\n tf.app.flags.DEFINE_string('run', None, \"Which operation to run. [train|inference]\")\n\n ##########################\n # Training parameters\n ###########################\n tf.app.flags.DEFINE_integer('nb_epoch', 400, \"Number of epochs\")\n tf.app.flags.DEFINE_integer('batch_size', 64, \"Number of samples per batch.\")\n tf.app.flags.DEFINE_integer('nb_batch_per_epoch', 500, \"Number of batches per epoch\")\n tf.app.flags.DEFINE_float('learning_rate', 2E-4, \"Learning rate used for AdamOptimizer\")\n tf.app.flags.DEFINE_integer('noise_dim', 100, \"Noise dimension for GAN generation\")\n tf.app.flags.DEFINE_integer('random_seed', 0, \"Seed used to initialize rng.\")\n\n ############################################\n # General tensorflow parameters parameters\n #############################################\n tf.app.flags.DEFINE_bool('use_XLA', False, \"Whether to use XLA compiler.\")\n tf.app.flags.DEFINE_integer('num_threads', 2, \"Number of threads to fetch the data\")\n tf.app.flags.DEFINE_float('capacity_factor', 32, \"Nuumber of batches to store in queue\")\n\n ##########\n # Datasets\n ##########\n tf.app.flags.DEFINE_string('data_format', \"NCHW\", \"Tensorflow image data format.\")\n tf.app.flags.DEFINE_string('celebA_path', \"../../data/raw/img_align_celeba\", \"Path to celebA images\")\n tf.app.flags.DEFINE_integer('channels', 3, \"Number of channels\")\n tf.app.flags.DEFINE_float('central_fraction', 0.8, \"Central crop as a fraction of total image\")\n tf.app.flags.DEFINE_integer('img_size', 64, \"Image size\")\n\n ##############\n # Directories\n ##############\n tf.app.flags.DEFINE_string('model_dir', '../../models', \"Output folder where checkpoints are dumped.\")\n tf.app.flags.DEFINE_string('log_dir', '../../logs', \"Logs for tensorboard.\")\n tf.app.flags.DEFINE_string('fig_dir', '../../figures', \"Where to save figures.\")\n tf.app.flags.DEFINE_string('raw_dir', '../../data/raw', \"Where raw data is saved\")\n tf.app.flags.DEFINE_string('data_dir', '../../data/processed', \"Where processed data is saved\")\n", "import os\nimport numpy as np\nfrom skimage import color\nimport matplotlib.pylab as plt\n\n\ndef remove_files(files):\n \"\"\"\n Remove files from disk\n\n args: files (str or list) remove all files in 'files'\n \"\"\"\n\n if isinstance(files, (list, tuple)):\n for f in files:\n if os.path.isfile(os.path.expanduser(f)):\n os.remove(f)\n elif isinstance(files, str):\n if os.path.isfile(os.path.expanduser(files)):\n os.remove(files)\n\n\ndef create_dir(dirs):\n \"\"\"\n Create directory\n\n args: dirs (str or list) create all dirs in 'dirs'\n \"\"\"\n\n if isinstance(dirs, (list, tuple)):\n for d in dirs:\n if not os.path.exists(os.path.expanduser(d)):\n os.makedirs(d)\n elif isinstance(dirs, str):\n if not os.path.exists(os.path.expanduser(dirs)):\n os.makedirs(dirs)\n\n\ndef setup_logging(model_name):\n\n model_dir = \"../../models\"\n # Output path where we store experiment log and weights\n model_dir = os.path.join(model_dir, model_name)\n\n fig_dir = \"../../figures\"\n\n # Create if it does not exist\n create_dir([model_dir, fig_dir])\n\n\ndef plot_batch(color_model, q_ab, X_batch_black, X_batch_color, batch_size, h, w, nb_q, epoch):\n\n # Format X_colorized\n X_colorized = color_model.predict(X_batch_black / 100.)[:, :, :, :-1]\n X_colorized = X_colorized.reshape((batch_size * h * w, nb_q))\n X_colorized = q_ab[np.argmax(X_colorized, 1)]\n X_a = X_colorized[:, 0].reshape((batch_size, 1, h, w))\n X_b = X_colorized[:, 1].reshape((batch_size, 1, h, w))\n X_colorized = np.concatenate((X_batch_black, X_a, X_b), axis=1).transpose(0, 2, 3, 1)\n X_colorized = [np.expand_dims(color.lab2rgb(im), 0) for im in X_colorized]\n X_colorized = np.concatenate(X_colorized, 0).transpose(0, 3, 1, 2)\n\n X_batch_color = [np.expand_dims(color.lab2rgb(im.transpose(1, 2, 0)), 0) for im in X_batch_color]\n X_batch_color = np.concatenate(X_batch_color, 0).transpose(0, 3, 1, 2)\n\n list_img = []\n for i, img in enumerate(X_colorized[:min(32, batch_size)]):\n arr = np.concatenate([X_batch_color[i], np.repeat(X_batch_black[i] / 100., 3, axis=0), img], axis=2)\n list_img.append(arr)\n\n plt.figure(figsize=(20,20))\n list_img = [np.concatenate(list_img[4 * i: 4 * (i + 1)], axis=2) for i in range(len(list_img) // 4)]\n arr = np.concatenate(list_img, axis=1)\n plt.imshow(arr.transpose(1,2,0))\n ax = plt.gca()\n ax.get_xaxis().set_ticks([])\n ax.get_yaxis().set_ticks([])\n plt.tight_layout()\n plt.savefig(\"../../figures/fig_epoch%s.png\" % epoch)\n plt.clf()\n plt.close()\n\n\ndef plot_batch_eval(color_model, q_ab, X_batch_black, X_batch_color, batch_size, h, w, nb_q, T):\n\n # Format X_colorized\n X_colorized = color_model.predict(X_batch_black / 100.)[:, :, :, :-1]\n X_colorized = X_colorized.reshape((batch_size * h * w, nb_q))\n\n # Reweight probas\n X_colorized = np.exp(np.log(X_colorized) / T)\n X_colorized = X_colorized / np.sum(X_colorized, 1)[:, np.newaxis]\n\n # Reweighted\n q_a = q_ab[:, 0].reshape((1, 313))\n q_b = q_ab[:, 1].reshape((1, 313))\n\n X_a = np.sum(X_colorized * q_a, 1).reshape((batch_size, 1, h, w))\n X_b = np.sum(X_colorized * q_b, 1).reshape((batch_size, 1, h, w))\n\n X_colorized = np.concatenate((X_batch_black, X_a, X_b), axis=1).transpose(0, 2, 3, 1)\n X_colorized = [np.expand_dims(color.lab2rgb(im), 0) for im in X_colorized]\n X_colorized = np.concatenate(X_colorized, 0).transpose(0, 3, 1, 2)\n\n X_batch_color = [np.expand_dims(color.lab2rgb(im.transpose(1, 2, 0)), 0) for im in X_batch_color]\n X_batch_color = np.concatenate(X_batch_color, 0).transpose(0, 3, 1, 2)\n\n list_img = []\n for i, img in enumerate(X_colorized[:min(32, batch_size)]):\n arr = np.concatenate([X_batch_color[i], np.repeat(X_batch_black[i] / 100., 3, axis=0), img], axis=2)\n list_img.append(arr)\n\n plt.figure(figsize=(20,20))\n list_img = [np.concatenate(list_img[4 * i: 4 * (i + 1)], axis=2) for i in range(len(list_img) // 4)]\n arr = np.concatenate(list_img, axis=1)\n plt.imshow(arr.transpose(1,2,0))\n ax = plt.gca()\n ax.get_xaxis().set_ticks([])\n ax.get_yaxis().set_ticks([])\n plt.tight_layout()\n plt.show()\n", "import os\nimport sys\nimport models\nfrom tqdm import tqdm\nimport tensorflow as tf\nsys.path.append(\"../utils\")\nimport visualization_utils as vu\nimport training_utils as tu\nimport data_utils as du\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef train_model():\n\n # Setup session\n sess = tu.setup_session()\n\n # Setup async input queue of real images\n X_real = du.input_data(sess)\n\n #######################\n # Instantiate generator\n #######################\n list_filters = [256, 128, 64, 3]\n list_strides = [2] * len(list_filters)\n list_kernel_size = [3] * len(list_filters)\n list_padding = [\"SAME\"] * len(list_filters)\n output_shape = X_real.get_shape().as_list()[1:]\n G = models.Generator(list_filters, list_kernel_size, list_strides, list_padding, output_shape,\n batch_size=FLAGS.batch_size, data_format=FLAGS.data_format)\n\n ###########################\n # Instantiate discriminator\n ###########################\n list_filters = [32, 64, 128, 256]\n list_strides = [2] * len(list_filters)\n list_kernel_size = [3] * len(list_filters)\n list_padding = [\"SAME\"] * len(list_filters)\n D = models.Discriminator(list_filters, list_kernel_size, list_strides, list_padding,\n FLAGS.batch_size, data_format=FLAGS.data_format)\n\n ###########################\n # Instantiate optimizers\n ###########################\n G_opt = tf.train.AdamOptimizer(learning_rate=1E-4, name='G_opt', beta1=0.5, beta2=0.9)\n D_opt = tf.train.AdamOptimizer(learning_rate=1E-4, name='D_opt', beta1=0.5, beta2=0.9)\n\n ###########################\n # Instantiate model outputs\n ###########################\n\n # noise_input = tf.random_normal((FLAGS.batch_size, FLAGS.noise_dim,), stddev=0.1)\n noise_input = tf.random_uniform((FLAGS.batch_size, FLAGS.noise_dim,), minval=-1, maxval=1)\n X_fake = G(noise_input)\n\n # output images\n X_G_output = du.unnormalize_image(X_fake)\n X_real_output = du.unnormalize_image(X_real)\n\n D_real = D(X_real)\n D_fake = D(X_fake, reuse=True)\n\n ###########################\n # Instantiate losses\n ###########################\n\n G_loss = -tf.reduce_mean(D_fake)\n D_loss = tf.reduce_mean(D_fake) - tf.reduce_mean(D_real)\n\n epsilon = tf.random_uniform(\n shape=[FLAGS.batch_size, 1, 1, 1],\n minval=0.,\n maxval=1.\n )\n X_hat = X_real + epsilon * (X_fake - X_real)\n D_X_hat = D(X_hat, reuse=True)\n grad_D_X_hat = tf.gradients(D_X_hat, [X_hat])[0]\n if FLAGS.data_format == \"NCHW\":\n red_idx = [1]\n else:\n red_idx = [-1]\n slopes = tf.sqrt(tf.reduce_sum(tf.square(grad_D_X_hat), reduction_indices=red_idx))\n gradient_penalty = tf.reduce_mean((slopes - 1.)**2)\n D_loss += 10 * gradient_penalty\n\n ###########################\n # Compute gradient updates\n ###########################\n\n dict_G_vars = G.get_trainable_variables()\n G_vars = [dict_G_vars[k] for k in dict_G_vars.keys()]\n\n dict_D_vars = D.get_trainable_variables()\n D_vars = [dict_D_vars[k] for k in dict_D_vars.keys()]\n\n G_gradvar = G_opt.compute_gradients(G_loss, var_list=G_vars, colocate_gradients_with_ops=True)\n G_update = G_opt.apply_gradients(G_gradvar, name='G_loss_minimize')\n\n D_gradvar = D_opt.compute_gradients(D_loss, var_list=D_vars, colocate_gradients_with_ops=True)\n D_update = D_opt.apply_gradients(D_gradvar, name='D_loss_minimize')\n\n ##########################\n # Group training ops\n ##########################\n loss_ops = [G_loss, D_loss]\n\n ##########################\n # Summary ops\n ##########################\n\n # Add summary for gradients\n tu.add_gradient_summary(G_gradvar)\n tu.add_gradient_summary(D_gradvar)\n\n # Add scalar symmaries\n tf.summary.scalar(\"G loss\", G_loss)\n tf.summary.scalar(\"D loss\", D_loss)\n tf.summary.scalar(\"gradient_penalty\", gradient_penalty)\n\n summary_op = tf.summary.merge_all()\n\n ############################\n # Start training\n ############################\n\n # Initialize session\n saver = tu.initialize_session(sess)\n\n # Start queues\n tu.manage_queues(sess)\n\n # Summaries\n writer = tu.manage_summaries(sess)\n\n for e in tqdm(range(FLAGS.nb_epoch), desc=\"Training progress\"):\n\n t = tqdm(range(FLAGS.nb_batch_per_epoch), desc=\"Epoch %i\" % e, mininterval=0.5)\n for batch_counter in t:\n\n for di in range(5):\n sess.run([D_update])\n\n output = sess.run([G_update] + loss_ops + [summary_op])\n\n if batch_counter % (FLAGS.nb_batch_per_epoch // 20) == 0:\n writer.add_summary(output[-1], e * FLAGS.nb_batch_per_epoch + batch_counter)\n\n t.set_description('Epoch %i' % e)\n\n # Plot some generated images\n output = sess.run([X_G_output, X_real_output])\n vu.save_image(output, FLAGS.data_format, e)\n\n # Save session\n saver.save(sess, os.path.join(FLAGS.model_dir, \"model\"), global_step=e)\n\n print('Finished training!')\n" ]
[ [ "tensorflow.app.flags.DEFINE_bool", "tensorflow.app.flags.DEFINE_string", "tensorflow.app.flags.DEFINE_integer", "tensorflow.app.flags.DEFINE_float" ], [ "matplotlib.pylab.tight_layout", "matplotlib.pylab.show", "numpy.log", "numpy.sum", "numpy.repeat", "numpy.concatenate", "numpy.argmax", "matplotlib.pylab.gca", "matplotlib.pylab.figure", "matplotlib.pylab.clf", "matplotlib.pylab.savefig", "matplotlib.pylab.close" ], [ "tensorflow.summary.scalar", "tensorflow.reduce_mean", "tensorflow.gradients", "tensorflow.summary.merge_all", "tensorflow.train.AdamOptimizer", "tensorflow.square", "tensorflow.random_uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
kwangsungjun/lrbandit
[ "2f1f7ca4bbefe2bfd3e0bc50c4423a9791bfcde8" ]
[ "matrixrecovery/matrixrecovery.py" ]
[ "import myutils_cython\nimport numpy as np, numpy.random as ra, scipy.linalg as sla\nfrom tqdm import tqdm\n\ndef rankone(X,Z,y,r,R=.1, C=.1, tolPred=0.01, tolTh=0.01, maxIter=400, verbose=False):\n \"\"\"\n matrix recovery with rank-one measurements using Burer-Monteiro approach \n measurement model: (X[i,:] @ Theta) @ Z[i,:] == y[i]\n (IN)\n X, Z: N by d matrix\n y: N-dim vector\n r: the deemed rank of Theta\n R: noise level (subgaussian parameter)\n C: regularization parameter (larger => more regularization)\n tol: stopping condition\n maxIter: maximum number of iterations\n (OUT)\n (U,V,out_nIter,stat) so that [email protected] ≈ Theta;\n stat['objs'] has the objective values over time\n stat['stoppingPredList'], stat['stoppingThetaList'] has stopping conditions over time\n \"\"\"\n N,d = X.shape\n initU = ra.randn(d,r)\n U = initU\n V = initU # just a placeholder\n M = np.zeros( (d*r,d*r) )\n hatTh = initU @ initU.T # very bad initial hatTh\n if (verbose):\n my_tqdm = tqdm\n else:\n my_tqdm = lambda x: x\n\n objs = []; stoppingPredList = []; stoppingThetaList = []\n myeye = R*C*np.eye(d*r) \n for iIter in my_tqdm(range(1,1+maxIter)):\n D = np.zeros((N,d*r))\n if iIter % 2 == 0: # update U\n ZV = Z @ V\n myutils_cython.calcRowwiseKron(D, X, ZV) #- note D will be written!\n else: # update V\n XU = X @ U\n myutils_cython.calcRowwiseKron(D, Z, XU)\n\n M[:,:] = myeye + D.T@D\n b = D.T @ y\n sol = sla.solve(M,b, assume_a='pos', overwrite_a=True).reshape(d,r)\n if iIter % 2 == 0:\n prevU = U\n U = sol\n else:\n prevV = V\n V = sol\n prev_hatTh = hatTh\n hatTh = [email protected]\n #- compute residual\n predy = ((X@hatTh)*Z).sum(1)\n obj = sla.norm(predy - y, 2)**2 + R*C*(sla.norm(U, 'fro')**2 + sla.norm(V, 'fro')**2)\n objs.append( obj )\n stoppingPred = sla.norm(predy - y, 2) / sla.norm(y,2)\n stoppingPredList.append( stoppingPred )\n stoppingTheta = sla.norm(hatTh - prev_hatTh, 'fro')\n stoppingThetaList.append( stoppingTheta )\n if (stoppingPred < tolPred):\n break\n if (stoppingTheta < tolTh):\n break\n out_nIter = iIter\n stat = {'objs': objs, 'stoppingPredList': stoppingPredList, 'stoppingThetaList': stoppingThetaList}\n return U,V,out_nIter,stat\n\n" ]
[ [ "numpy.eye", "numpy.random.randn", "scipy.linalg.norm", "scipy.linalg.solve", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] } ]
kassyray/NeuroKit
[ "b84d110a71d5d17c0d1efde0d60d00446fda16cb", "b84d110a71d5d17c0d1efde0d60d00446fda16cb", "b84d110a71d5d17c0d1efde0d60d00446fda16cb" ]
[ "tests/tests_complexity.py", "neurokit2/rsp/rsp_process.py", "neurokit2/signal/signal_findpeaks.py" ]
[ "import numpy as np\nimport pandas as pd\nimport neurokit2 as nk\nimport nolds\n\nfrom pyentrp import entropy as pyentrp\n\n\"\"\"\nFor the testing of complexity, we test our implementations against existing and established ones.\nHowever, some of these other implementations are not really packaged in a way\nSO THAT we can easily import them. Thus, we directly copied their content in this file\n(below the tests).\n\"\"\"\n\n\n# =============================================================================\n# Some sanity checks\n# =============================================================================\ndef test_complexity_sanity():\n\n signal = np.cos(np.linspace(start=0, stop=30, num=1000))\n\n # Entropy\n assert np.allclose(nk.entropy_fuzzy(signal), nk.entropy_sample(signal, fuzzy=True), atol=0.000001)\n\n # Fractal\n assert np.allclose(nk.fractal_dfa(signal, windows=np.array([4, 8, 12, 20])), 2.1009048365682133, atol=0.000001)\n assert np.allclose(nk.fractal_dfa(signal), 1.957966586191164, atol=0.000001)\n assert np.allclose(nk.fractal_dfa(signal, multifractal=True), 1.957966586191164, atol=0.000001)\n\n assert np.allclose(nk.fractal_correlation(signal), 0.7884473170763334, atol=0.000001)\n assert np.allclose(nk.fractal_correlation(signal, r=\"nolds\"), nolds.corr_dim(signal, 2), atol=0.0001)\n\n\n# =============================================================================\n# Comparison against R\n# =============================================================================\n\"\"\"\nR code:\n\nlibrary(TSEntropies)\nlibrary(pracma)\n\nsignal <- read.csv(\"https://raw.githubusercontent.com/neuropsychology/NeuroKit/master/data/bio_eventrelated_100hz.csv\")$RSP\nr <- 0.2 * sd(signal)\n\n# ApEn --------------------------------------------------------------------\n\nTSEntropies::ApEn(signal, dim=2, lag=1, r=r)\n0.04383386\nTSEntropies::ApEn(signal, dim=3, lag=2, r=1)\n0.0004269369\npracma::approx_entropy(signal[1:200], edim=2, r=r, elag=1)\n0.03632554\n\n# SampEn ------------------------------------------------------------------\n\nTSEntropies::SampEn(signal[1:300], dim=2, lag=1, r=r)\n0.04777648\nTSEntropies::FastSampEn(signal[1:300], dim=2, lag=1, r=r)\n0.003490405\npracma::sample_entropy(signal[1:300], edim=2, tau=1, r=r)\n0.03784376\npracma::sample_entropy(signal[1:300], edim=3, tau=2, r=r)\n0.09185509\n\"\"\"\n\n\ndef test_complexity_vs_R():\n\n signal = pd.read_csv(\"https://raw.githubusercontent.com/neuropsychology/NeuroKit/master/data/bio_eventrelated_100hz.csv\")[\"RSP\"].values\n r = 0.2 * np.std(signal, ddof=1)\n\n # ApEn\n apen = nk.entropy_approximate(signal, dimension=2, r=r)\n assert np.allclose(apen, 0.04383386, atol=0.0001)\n apen = nk.entropy_approximate(signal, dimension=3, delay=2, r=1)\n assert np.allclose(apen, 0.0004269369, atol=0.0001)\n apen = nk.entropy_approximate(signal[0:200], dimension=2, delay=1, r=r)\n assert np.allclose(apen, 0.03632554, atol=0.0001)\n\n # SampEn\n sampen = nk.entropy_sample(signal[0:300], dimension=2, r=r)\n assert np.allclose(sampen, nk.entropy_sample(signal[0:300], dimension=2, r=r, distance=\"infinity\"), atol=0.001)\n assert np.allclose(sampen, 0.03784376, atol=0.001)\n sampen = nk.entropy_sample(signal[0:300], dimension=3, delay=2, r=r)\n assert np.allclose(sampen, 0.09185509, atol=0.01)\n\n\n# =============================================================================\n# Comparison against Python implementations\n# =============================================================================\n\n\ndef test_complexity_vs_Python():\n\n signal = np.cos(np.linspace(start=0, stop=30, num=100))\n\n # Shannon\n shannon = nk.entropy_shannon(signal)\n# assert scipy.stats.entropy(shannon, pd.Series(signal).value_counts())\n assert np.allclose(shannon - pyentrp.shannon_entropy(signal), 0)\n\n\n # Approximate\n assert np.allclose(nk.entropy_approximate(signal), 0.17364897858477146)\n assert np.allclose(nk.entropy_approximate(signal, dimension=2, r=0.2*np.std(signal, ddof=1)) - entropy_app_entropy(signal, 2), 0)\n\n assert nk.entropy_approximate(signal, dimension=2, r=0.2*np.std(signal, ddof=1)) != pyeeg_ap_entropy(signal, 2, 0.2*np.std(signal, ddof=1))\n\n\n # Sample\n assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2*np.std(signal, ddof=1)) - entropy_sample_entropy(signal, 2), 0)\n assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2) - nolds.sampen(signal, 2, 0.2), 0)\n assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2) - entro_py_sampen(signal, 2, 0.2, scale=False), 0)\n assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2) - pyeeg_samp_entropy(signal, 2, 0.2), 0)\n\n# import sampen\n# sampen.sampen2(signal[0:300], mm=2, r=r)\n\n assert nk.entropy_sample(signal, dimension=2, r=0.2) != pyentrp.sample_entropy(signal, 2, 0.2)[1]\n assert nk.entropy_sample(signal, dimension=2, r=0.2*np.sqrt(np.var(signal))) != MultiscaleEntropy_sample_entropy(signal, 2, 0.2)[0.2][2]\n\n # MSE\n# assert nk.entropy_multiscale(signal, 2, 0.2*np.sqrt(np.var(signal))) != np.trapz(MultiscaleEntropy_mse(signal, [i+1 for i in range(10)], 2, 0.2, return_type=\"list\"))\n# assert nk.entropy_multiscale(signal, 2, 0.2*np.std(signal, ddof=1)) != np.trapz(pyentrp.multiscale_entropy(signal, 2, 0.2, 10))\n\n # Fuzzy\n assert np.allclose(nk.entropy_fuzzy(signal, dimension=2, r=0.2, delay=1) - entro_py_fuzzyen(signal, 2, 0.2, 1, scale=False), 0)\n\n # DFA\n assert nk.fractal_dfa(signal, windows=np.array([4, 8, 12, 20])) != nolds.dfa(signal, nvals=[4, 8, 12, 20], fit_exp=\"poly\")\n\n\n# =============================================================================\n# Wikipedia\n# =============================================================================\ndef wikipedia_sampen(signal, m=2, r=1):\n N = len(signal)\n B = 0.0\n A = 0.0\n\n # Split time series and save all templates of length m\n xmi = np.array([signal[i : i + m] for i in range(N - m)])\n xmj = np.array([signal[i : i + m] for i in range(N - m + 1)])\n\n # Save all matches minus the self-match, compute B\n B = np.sum([np.sum(np.abs(xmii - xmj).max(axis=1) <= r) - 1 for xmii in xmi])\n\n # Similar for computing A\n m += 1\n xm = np.array([signal[i : i + m] for i in range(N - m + 1)])\n\n A = np.sum([np.sum(np.abs(xmi - xm).max(axis=1) <= r) - 1 for xmi in xm])\n\n # Return SampEn\n return -np.log(A / B)\n\n\n# =============================================================================\n# Pyeeg\n# =============================================================================\n\n\ndef pyeeg_embed_seq(time_series, tau, embedding_dimension):\n if not type(time_series) == np.ndarray:\n typed_time_series = np.asarray(time_series)\n else:\n typed_time_series = time_series\n\n shape = (\n typed_time_series.size - tau * (embedding_dimension - 1),\n embedding_dimension\n )\n\n strides = (typed_time_series.itemsize, tau * typed_time_series.itemsize)\n\n return np.lib.stride_tricks.as_strided(\n typed_time_series,\n shape=shape,\n strides=strides\n )\n\n\n\n\ndef pyeeg_bin_power(X, Band, Fs):\n C = np.fft.fft(X)\n C = abs(C)\n Power = np.zeros(len(Band) - 1)\n for Freq_Index in range(0, len(Band) - 1):\n Freq = float(Band[Freq_Index])\n Next_Freq = float(Band[Freq_Index + 1])\n Power[Freq_Index] = sum(\n C[int(np.floor(Freq / Fs * len(X))):\n int(np.floor(Next_Freq / Fs * len(X)))]\n )\n Power_Ratio = Power / sum(Power)\n return Power, Power_Ratio\n\n\n\n\n\ndef pyeeg_ap_entropy(X, M, R):\n N = len(X)\n\n Em = pyeeg_embed_seq(X, 1, M)\n A = np.tile(Em, (len(Em), 1, 1))\n B = np.transpose(A, [1, 0, 2])\n D = np.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|\n InRange = np.max(D, axis=2) <= R\n\n # Probability that random M-sequences are in range\n Cm = InRange.mean(axis=0)\n\n # M+1-sequences in range if M-sequences are in range & last values are close\n Dp = np.abs(\n np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T\n )\n\n Cmp = np.logical_and(Dp <= R, InRange[:-1, :-1]).mean(axis=0)\n\n Phi_m, Phi_mp = np.sum(np.log(Cm)), np.sum(np.log(Cmp))\n\n Ap_En = (Phi_m - Phi_mp) / (N - M)\n\n return Ap_En\n\n\ndef pyeeg_samp_entropy(X, M, R):\n N = len(X)\n\n Em = pyeeg_embed_seq(X, 1, M)[:-1]\n A = np.tile(Em, (len(Em), 1, 1))\n B = np.transpose(A, [1, 0, 2])\n D = np.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|\n InRange = np.max(D, axis=2) <= R\n np.fill_diagonal(InRange, 0) # Don't count self-matches\n\n Cm = InRange.sum(axis=0) # Probability that random M-sequences are in range\n Dp = np.abs(\n np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T\n )\n\n Cmp = np.logical_and(Dp <= R, InRange).sum(axis=0)\n\n # Avoid taking log(0)\n Samp_En = np.log(np.sum(Cm + 1e-100) / np.sum(Cmp + 1e-100))\n\n return Samp_En\n\n# =============================================================================\n# Entropy\n# =============================================================================\n\n\nfrom sklearn.neighbors import KDTree\n\ndef entropy_embed(x, order=3, delay=1):\n N = len(x)\n if order * delay > N:\n raise ValueError(\"Error: order * delay should be lower than x.size\")\n if delay < 1:\n raise ValueError(\"Delay has to be at least 1.\")\n if order < 2:\n raise ValueError(\"Order has to be at least 2.\")\n Y = np.zeros((order, N - (order - 1) * delay))\n for i in range(order):\n Y[i] = x[i * delay:i * delay + Y.shape[1]]\n return Y.T\n\n\n\ndef entropy_app_samp_entropy(x, order, metric='chebyshev', approximate=True):\n _all_metrics = KDTree.valid_metrics\n if metric not in _all_metrics:\n raise ValueError('The given metric (%s) is not valid. The valid '\n 'metric names are: %s' % (metric, _all_metrics))\n phi = np.zeros(2)\n r = 0.2 * np.std(x, axis=-1, ddof=1)\n\n # compute phi(order, r)\n _emb_data1 = entropy_embed(x, order, 1)\n if approximate:\n emb_data1 = _emb_data1\n else:\n emb_data1 = _emb_data1[:-1]\n count1 = KDTree(emb_data1, metric=metric).query_radius(emb_data1, r,\n count_only=True\n ).astype(np.float64)\n # compute phi(order + 1, r)\n emb_data2 = entropy_embed(x, order + 1, 1)\n count2 = KDTree(emb_data2, metric=metric).query_radius(emb_data2, r,\n count_only=True\n ).astype(np.float64)\n if approximate:\n phi[0] = np.mean(np.log(count1 / emb_data1.shape[0]))\n phi[1] = np.mean(np.log(count2 / emb_data2.shape[0]))\n else:\n phi[0] = np.mean((count1 - 1) / (emb_data1.shape[0] - 1))\n phi[1] = np.mean((count2 - 1) / (emb_data2.shape[0] - 1))\n return phi\n\n\n\n\ndef entropy_app_entropy(x, order=2, metric='chebyshev'):\n phi = entropy_app_samp_entropy(x, order=order, metric=metric, approximate=True)\n return np.subtract(phi[0], phi[1])\n\n\n\ndef entropy_sample_entropy(x, order=2, metric='chebyshev'):\n x = np.asarray(x, dtype=np.float64)\n phi = entropy_app_samp_entropy(x, order=order, metric=metric,\n approximate=False)\n return -np.log(np.divide(phi[1], phi[0]))\n\n\n\n# =============================================================================\n# entro-py\n# =============================================================================\n\ndef entro_py_sampen(x, dim, r, scale=True):\n return entro_py_entropy(x, dim, r, scale=scale)\n\n\ndef entro_py_cross_sampen(x1, x2, dim, r, scale=True):\n return entro_py_entropy([x1, x2], dim, r, scale)\n\n\ndef entro_py_fuzzyen(x, dim, r, n, scale=True):\n return entro_py_entropy(x, dim, r, n=n, scale=scale, remove_baseline=True)\n\n\ndef entro_py_cross_fuzzyen(x1, x2, dim, r, n, scale=True):\n return entro_py_entropy([x1, x2], dim, r, n, scale=scale, remove_baseline=True)\n\n\ndef entro_py_pattern_mat(x, m):\n x = np.asarray(x).ravel()\n if m == 1:\n return x\n else:\n N = len(x)\n patterns = np.zeros((m, N-m+1))\n for i in range(m):\n patterns[i, :] = x[i:N-m+i+1]\n return patterns\n\n\ndef entro_py_entropy(x, dim, r, n=1, scale=True, remove_baseline=False):\n fuzzy = True if remove_baseline else False\n cross = True if type(x) == list else False\n N = len(x[0]) if cross else len(x)\n\n if scale:\n if cross:\n x = [entro_py_scale(np.copy(x[0])), entro_py_scale(np.copy(x[1]))]\n else:\n x = entro_py_scale(np.copy(x))\n\n phi = [0, 0] # phi(m), phi(m+1)\n for j in [0, 1]:\n m = dim + j\n npat = N-dim # https://github.com/ixjlyons/entro-py/pull/2/files\n if cross:\n# patterns = [entro_py_pattern_mat(x[0], m), entro_py_pattern_mat(x[1], m)]\n patterns = [entro_py_pattern_mat(x[0], m)[:, :npat], entro_py_pattern_mat(x[1], m)[:, :npat]] # https://github.com/ixjlyons/entro-py/pull/2/files\n else:\n# patterns = entro_py_pattern_mat(x, m)\n patterns = entro_py_pattern_mat(x, m)[:, :npat]\n\n if remove_baseline:\n if cross:\n patterns[0] = entro_py_remove_baseline(patterns[0], axis=0)\n patterns[1] = entro_py_remove_baseline(patterns[1], axis=0)\n else:\n patterns = entro_py_remove_baseline(patterns, axis=0)\n\n# count = np.zeros(N-m) # https://github.com/ixjlyons/entro-py/pull/2/files\n# for i in range(N-m): # https://github.com/ixjlyons/entro-py/pull/2/files\n count = np.zeros(npat)\n for i in range(npat):\n if cross:\n if m == 1:\n sub = patterns[1][i]\n else:\n sub = patterns[1][:, [i]]\n dist = np.max(np.abs(patterns[0] - sub), axis=0)\n else:\n if m == 1:\n sub = patterns[i]\n else:\n sub = patterns[:, [i]]\n dist = np.max(np.abs(patterns - sub), axis=0)\n\n if fuzzy:\n sim = np.exp(-np.power(dist, n) / r)\n else:\n sim = dist < r\n\n count[i] = np.sum(sim) - 1\n\n# phi[j] = np.mean(count) / (N-m-1)\n phi[j] = np.mean(count) / (N-dim-1) # https://github.com/ixjlyons/entro-py/pull/2/files\n\n return np.log(phi[0] / phi[1])\n\n\ndef entro_py_scale(x, axis=None):\n x = entro_py_remove_baseline(x, axis=axis)\n x /= np.std(x, ddof=1, axis=axis, keepdims=True)\n return x\n\n\ndef entro_py_remove_baseline(x, axis=None):\n x -= np.mean(x, axis=axis, keepdims=True)\n return x\n\n\n\n\n\n\n\n\n\n\n\n\n\n# =============================================================================\n# MultiscaleEntropy https://github.com/reatank/MultiscaleEntropy/blob/master/MultiscaleEntropy/mse.py\n# =============================================================================\n\nimport math\nfrom collections.abc import Iterable\n\ndef MultiscaleEntropy_init_return_type(return_type):\n if return_type == 'dict':\n return {}\n else:\n return []\n\ndef MultiscaleEntropy_check_type(x, num_type, name):\n if isinstance(x, num_type):\n tmp = [x]\n elif not isinstance(x, Iterable):\n raise ValueError(name + ' should be a ' + num_type.__name__ + ' or an iterator of ' + num_type.__name__)\n else:\n tmp = []\n for i in x:\n tmp.append(i)\n if not isinstance(i, num_type):\n raise ValueError(name + ' should be a ' + num_type.__name__ + ' or an iterator of ' + num_type.__name__)\n return tmp\n\n# sum of seperate intervals of x\ndef MultiscaleEntropy_coarse_grain(x, scale_factor):\n x = np.array(x)\n x_len = len(x)\n if x_len % scale_factor:\n padded_len = (1+int(x_len/scale_factor))*scale_factor\n else:\n padded_len = x_len\n tmp_x = np.zeros(padded_len)\n tmp_x[:x_len] = x\n tmp_x = np.reshape(tmp_x, (int(padded_len/scale_factor), scale_factor))\n ans = np.reshape(np.sum(tmp_x, axis=1), (-1))/scale_factor\n\n return ans\n\ndef MultiscaleEntropy_sample_entropy(x, m=[2], r=[0.15], sd=None, return_type='dict', safe_mode=False):\n '''[Sample Entropy, the threshold will be r*sd]\n\n Arguments:\n x {[input signal]} -- [an iterator of numbers]\n\n Keyword Arguments:\n m {list} -- [m in sample entropy] (default: {[2]})\n r {list} -- [r in sample entropy] (default: {[0.15]})\n sd {number} -- [standard derivation of x, if None, will be calculated] (default: {None})\n return_type {str} -- [can be dict or list] (default: {'dict'})\n safe_mode {bool} -- [if set True, type checking will be skipped] (default: {False})\n\n Raises:\n ValueError -- [some values too big]\n\n Returns:\n [dict or list as return_type indicates] -- [if dict, nest as [scale_factor][m][r] for each value of m, r; if list, nest as [i][j] for lengths of m, r]\n '''\n # type checking\n if not safe_mode:\n m = MultiscaleEntropy_check_type(m, int, 'm')\n r = MultiscaleEntropy_check_type(r, float, 'r')\n if not (sd == None) and not (isinstance(sd, float) or isinstance(sd, int)):\n raise ValueError('sd should be a number')\n try:\n x = np.array(x)\n except:\n raise ValueError('x should be a sequence of numbers')\n # value checking\n if len(x) < max(m):\n raise ValueError('the max m is bigger than x\\'s length')\n\n # initialization\n if sd == None:\n sd = np.sqrt(np.var(x))\n ans = MultiscaleEntropy_init_return_type(return_type)\n\n # calculation\n for i, rr in enumerate(r):\n threshold = rr * sd\n if return_type == 'dict':\n ans[rr] = MultiscaleEntropy_init_return_type(return_type)\n else:\n ans.append(MultiscaleEntropy_init_return_type(return_type))\n count = {}\n tmp_m = []\n for mm in m:\n tmp_m.append(mm)\n tmp_m.append(mm+1)\n tmp_m = list(set(tmp_m))\n for mm in tmp_m:\n count[mm] = 0\n\n for j in range(1, len(x)-min(m)+1):\n cont = 0\n for inc in range(0, len(x)-j):\n if abs(x[inc]-x[j+inc]) < threshold:\n cont += 1\n elif cont > 0:\n for mm in tmp_m:\n tmp = cont - mm + 1\n count[mm] += tmp if tmp > 0 else 0\n cont = 0\n if cont > 0:\n for mm in tmp_m:\n tmp = cont - mm + 1\n count[mm] += tmp if tmp > 0 else 0\n for mm in m:\n if count[mm+1] == 0 or count[mm] == 0:\n t = len(x)-mm+1\n tmp = -math.log(1/(t*(t-1)))\n else:\n tmp = -math.log(count[mm+1]/count[mm])\n if return_type == 'dict':\n ans[rr][mm] = tmp\n else:\n ans[i].append(tmp)\n return ans\n\ndef MultiscaleEntropy_mse(x, scale_factor=[i for i in range(1,21)], m=[2], r=[0.15], return_type='dict', safe_mode=False):\n '''[Multiscale Entropy]\n\n Arguments:\n x {[input signal]} -- [an iterator of numbers]\n\n Keyword Arguments:\n scale_factor {list} -- [scale factors of coarse graining] (default: {[i for i in range(1,21)]})\n m {list} -- [m in sample entropy] (default: {[2]})\n r {list} -- [r in sample entropy] (default: {[0.15]})\n return_type {str} -- [can be dict or list] (default: {'dict'})\n safe_mode {bool} -- [if set True, type checking will be skipped] (default: {False})\n\n Raises:\n ValueError -- [some values too big]\n\n Returns:\n [dict or list as return_type indicates] -- [if dict, nest as [scale_factor][m][r] for each value of scale_factor, m, r; if list nest as [i][j][k] for lengths of scale_factor, m, r]\n '''\n # type checking\n if not safe_mode:\n m = MultiscaleEntropy_check_type(m, int, 'm')\n r = MultiscaleEntropy_check_type(r, float, 'r')\n scale_factor = MultiscaleEntropy_check_type(scale_factor, int, 'scale_factor')\n try:\n x = np.array(x)\n except:\n print('x should be a sequence of numbers')\n # value checking\n if max(scale_factor) > len(x):\n raise ValueError('the max scale_factor is bigger than x\\'s length')\n\n # calculation\n sd = np.sqrt(np.var(x))\n ms_en = MultiscaleEntropy_init_return_type(return_type)\n for s_f in scale_factor:\n y = MultiscaleEntropy_coarse_grain(x, s_f)\n if return_type == 'dict':\n ms_en[s_f] = MultiscaleEntropy_sample_entropy(y, m, r, sd, 'dict', True)\n else:\n ms_en.append(MultiscaleEntropy_sample_entropy(y, m, r, sd, 'list', True))\n\n if return_type == \"list\":\n ms_en = [i[0] for i in ms_en]\n ms_en = [i[0] for i in ms_en]\n return ms_en\n", "# -*- coding: utf-8 -*-\nimport pandas as pd\n\nfrom ..signal import signal_rate\nfrom .rsp_amplitude import rsp_amplitude\nfrom .rsp_clean import rsp_clean\nfrom .rsp_peaks import rsp_peaks\nfrom .rsp_phase import rsp_phase\n\n\ndef rsp_process(rsp_signal, sampling_rate=1000, method=\"khodadad2018\"):\n \"\"\"Process a respiration (RSP) signal.\n\n Convenience function that automatically processes a respiration signal with one of the following methods:\n\n - `Khodadad et al. (2018)\n <https://iopscience.iop.org/article/10.1088/1361-6579/aad7e6/meta>`_\n\n - `BioSPPy\n <https://github.com/PIA-Group/BioSPPy/blob/master/biosppy/signals/resp.py>`_\n\n Parameters\n ----------\n rsp_signal : list, array or Series\n The raw respiration channel (as measured, for instance, by a respiration belt).\n sampling_rate : int\n The sampling frequency of `rsp_signal` (in Hz, i.e., samples/second).\n method : str\n The processing pipeline to apply. Can be one of \"khodadad2018\" (default) or \"biosppy\".\n\n Returns\n -------\n signals : DataFrame\n A DataFrame of same length as `rsp_signal` containing the following\n columns:\n - *\"RSP_Raw\"*: the raw signal.\n - *\"RSP_Clean\"*: the cleaned signal.\n - *\"RSP_Peaks\"*: the inhalation peaks marked as \"1\" in a list of zeros.\n - *\"RSP_Troughs\"*: the exhalation troughs marked as \"1\" in a list of zeros.\n - *\"RSP_Rate\"*: breathing rate interpolated between inhalation peaks.\n - *\"RSP_Amplitude\"*: breathing amplitude interpolated between inhalation peaks.\n - *\"RSP_Phase\"*: breathing phase, marked by \"1\" for inspiration and \"0\" for expiration.\n - *\"RSP_PhaseCompletion\"*: breathing phase completion, expressed in percentage (from 0 to 1),\n representing the stage of the current respiratory phase.\n info : dict\n A dictionary containing the samples at which inhalation peaks and exhalation troughs occur,\n accessible with the keys \"RSP_Peaks\", and \"RSP_Troughs\", respectively.\n\n See Also\n --------\n rsp_clean, rsp_findpeaks, signal_rate, rsp_amplitude, rsp_plot\n\n Examples\n --------\n >>> import neurokit2 as nk\n >>>\n >>> rsp = nk.rsp_simulate(duration=90, respiratory_rate=15)\n >>> signals, info = nk.rsp_process(rsp, sampling_rate=1000)\n >>> fig = nk.rsp_plot(signals)\n >>> fig #doctest: +SKIP\n\n \"\"\"\n # Clean signal\n rsp_cleaned = rsp_clean(rsp_signal, sampling_rate=sampling_rate, method=method)\n\n # Extract, fix and format peaks\n peak_signal, info = rsp_peaks(rsp_cleaned, sampling_rate=sampling_rate, method=method, amplitude_min=0.3)\n\n # Get additional parameters\n phase = rsp_phase(peak_signal)\n amplitude = rsp_amplitude(rsp_cleaned, peak_signal)\n rate = signal_rate(peak_signal, sampling_rate=sampling_rate)\n\n # Prepare output\n signals = pd.DataFrame(\n {\"RSP_Raw\": rsp_signal, \"RSP_Clean\": rsp_cleaned, \"RSP_Amplitude\": amplitude, \"RSP_Rate\": rate}\n )\n signals = pd.concat([signals, phase, peak_signal], axis=1)\n\n return signals, info\n", "# -*- coding: utf-8 -*-\nimport numpy as np\nimport scipy.misc\nimport scipy.signal\n\nfrom ..misc import as_vector, find_closest\nfrom ..stats import standardize\n\n\ndef signal_findpeaks(\n signal,\n height_min=None,\n height_max=None,\n relative_height_min=None,\n relative_height_max=None,\n relative_mean=True,\n relative_median=False,\n relative_max=False,\n):\n \"\"\"Find peaks in a signal.\n\n Locate peaks (local maxima) in a signal and their related characteristics, such as height (prominence),\n width and distance with other peaks.\n\n Parameters\n ----------\n signal : list or array or Series\n The signal (i.e., a time series) in the form of a vector of values.\n height_min : float\n The minimum height (i.e., amplitude in terms of absolute values). For example,`height_min=20`\n will remove all peaks which height is smaller or equal to 20 (in the provided signal's values).\n height_max : float\n The maximum height (i.e., amplitude in terms of absolute values).\n relative_height_min : float\n The minimum height (i.e., amplitude) relative to the sample (see below). For example,\n `relative_height_min=-2.96` will remove all peaks which height lies below 2.96 standard deviations\n from the mean of the heights.\n relative_height_max : float\n The maximum height (i.e., amplitude) relative to the sample (see below).\n relative_mean : bool\n If a relative threshold is specified, how should it be computed (i.e., relative to what?).\n `relative_mean=True` will use Z-scores.\n relative_median : bool\n If a relative threshold is specified, how should it be computed (i.e., relative to what?).\n Relative to median uses a more robust form of standardization (see `standardize`).\n relative_max : bool\n If a relative threshold is specified, how should it be computed (i.e., relative to what?).\n Reelative to max will consider the maximum height as the reference.\n\n Returns\n ----------\n dict\n Returns a dict itself containing 5 arrays:\n - 'Peaks' contains the peaks indices (as relative to the given signal). For instance, the\n value 3 means that the third data point of the signal is a peak.\n - 'Distance' contains, for each peak, the closest distance with another peak. Note that these\n values will be recomputed after filtering to match the selected peaks.\n - 'Height' contains the prominence of each peak. See `scipy.signal.peak_prominences()`.\n - 'Width' contains the width of each peak. See `scipy.signal.peak_widths()`.\n - 'Onset' contains the onset, start (or left trough), of each peak.\n - 'Offset' contains the offset, end (or right trough), of each peak.\n\n Examples\n ---------\n >>> import numpy as np\n >>> import pandas as pd\n >>> import neurokit2 as nk\n >>> import scipy.misc\n >>>\n >>> signal = nk.signal_simulate(duration=5)\n >>> info = nk.signal_findpeaks(signal)\n >>> fig1 = nk.events_plot([info[\"Onsets\"], info[\"Peaks\"]], signal)\n >>> fig1 #doctest: +SKIP\n >>>\n >>> signal = nk.signal_distort(signal)\n >>> info = nk.signal_findpeaks(signal, height_min=1)\n >>> fig2 = nk.events_plot(info[\"Peaks\"], signal)\n >>> fig2 #doctest: +SKIP\n >>>\n >>> # Filter peaks\n >>> ecg = scipy.misc.electrocardiogram()\n >>> signal = ecg[0:1000]\n >>> info1 = nk.signal_findpeaks(signal, relative_height_min=0)\n >>> info2 = nk.signal_findpeaks(signal, relative_height_min=1)\n >>> fig3 = nk.events_plot([info1[\"Peaks\"], info2[\"Peaks\"]], signal)\n >>> fig3 #doctest: +SKIP\n\n See Also\n --------\n scipy.signal.find_peaks, scipy.signal.peak_widths, peak_prominences.signal.peak_widths, eda_findpeaks,\n ecg_findpeaks, rsp_findpeaks, signal_fixpeaks\n\n \"\"\"\n info = _signal_findpeaks_scipy(signal)\n\n # Absolute\n info = _signal_findpeaks_keep(\n info,\n what=\"Height\",\n below=height_max,\n above=height_min,\n relative_mean=False,\n relative_median=False,\n relative_max=False,\n )\n\n # Relative\n info = _signal_findpeaks_keep(\n info,\n what=\"Height\",\n below=relative_height_max,\n above=relative_height_min,\n relative_mean=relative_mean,\n relative_median=relative_median,\n relative_max=relative_max,\n )\n\n # Filter\n info[\"Distance\"] = _signal_findpeaks_distances(info[\"Peaks\"])\n info[\"Onsets\"] = _signal_findpeaks_findbase(info[\"Peaks\"], signal, what=\"onset\")\n info[\"Offsets\"] = _signal_findpeaks_findbase(info[\"Peaks\"], signal, what=\"offset\")\n\n return info\n\n\n# =============================================================================\n# Filtering peaks\n# =============================================================================\n\n\ndef _signal_findpeaks_keep(\n info, what=\"Height\", below=None, above=None, relative_mean=False, relative_median=False, relative_max=False\n):\n\n if below is None and above is None:\n return info\n\n keep = np.full(len(info[\"Peaks\"]), True)\n\n if relative_max is True:\n what = info[what] / np.max(info[what])\n elif relative_median is True:\n what = standardize(info[what], robust=True)\n elif relative_mean is True:\n what = standardize(info[what])\n else:\n what = info[what]\n\n if below is not None:\n keep[what > below] = False\n if above is not None:\n keep[what < above] = False\n\n info = _signal_findpeaks_filter(info, keep)\n return info\n\n\ndef _signal_findpeaks_filter(info, keep):\n for key in info.keys():\n info[key] = info[key][keep]\n\n return info\n\n\n# =============================================================================\n# Helpers\n# =============================================================================\n\n\ndef _signal_findpeaks_distances(peaks):\n\n if len(peaks) <= 2:\n distances = np.full(len(peaks), np.nan)\n else:\n distances_next = np.concatenate([[np.nan], np.abs(np.diff(peaks))])\n distances_prev = np.concatenate([np.abs(np.diff(peaks[::-1])), [np.nan]])\n distances = np.array([np.nanmin(i) for i in list(zip(distances_next, distances_prev))])\n\n return distances\n\n\ndef _signal_findpeaks_findbase(peaks, signal, what=\"onset\"):\n if what == \"onset\":\n direction = \"smaller\"\n else:\n direction = \"greater\"\n\n troughs, _ = scipy.signal.find_peaks(-1 * signal)\n\n bases = find_closest(peaks, troughs, direction=direction, strictly=True)\n bases = as_vector(bases)\n\n return bases\n\n\ndef _signal_findpeaks_scipy(signal):\n peaks, _ = scipy.signal.find_peaks(signal)\n\n # Get info\n distances = _signal_findpeaks_distances(peaks)\n heights, __, __ = scipy.signal.peak_prominences(signal, peaks)\n widths, __, __, __ = scipy.signal.peak_widths(signal, peaks, rel_height=0.5)\n\n # Prepare output\n info = {\"Peaks\": peaks, \"Distance\": distances, \"Height\": heights, \"Width\": widths}\n\n return info\n" ]
[ [ "numpy.linspace", "numpy.asarray", "sklearn.neighbors.KDTree", "numpy.lib.stride_tricks.as_strided", "numpy.max", "numpy.mean", "numpy.fill_diagonal", "numpy.var", "numpy.divide", "pandas.read_csv", "numpy.allclose", "numpy.subtract", "numpy.std", "numpy.copy", "numpy.zeros", "numpy.log", "numpy.power", "numpy.transpose", "numpy.logical_and", "numpy.array", "numpy.sum", "numpy.abs", "numpy.fft.fft", "numpy.tile" ], [ "pandas.concat", "pandas.DataFrame" ], [ "numpy.max", "numpy.nanmin", "numpy.diff" ] ]
[ { "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", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shangz-ai/transformers
[ "75259b44bf2e2b98b5a4d431fb400b7190342a01", "75259b44bf2e2b98b5a4d431fb400b7190342a01", "75259b44bf2e2b98b5a4d431fb400b7190342a01", "75259b44bf2e2b98b5a4d431fb400b7190342a01", "75259b44bf2e2b98b5a4d431fb400b7190342a01", "75259b44bf2e2b98b5a4d431fb400b7190342a01" ]
[ "tests/models/tapas/test_tokenization_tapas.py", "tests/models/big_bird/test_modeling_big_bird.py", "src/transformers/models/longformer/modeling_longformer.py", "src/transformers/models/xlm/modeling_xlm.py", "tests/models/lxmert/test_modeling_lxmert.py", "src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py" ]
[ "# coding=utf-8\n# Copyright 2020 The HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport inspect\nimport os\nimport shutil\nimport tempfile\nimport unittest\nfrom typing import List\n\nimport numpy as np\nimport pandas as pd\n\nfrom transformers import AddedToken\nfrom transformers.models.tapas.tokenization_tapas import (\n VOCAB_FILES_NAMES,\n BasicTokenizer,\n TapasTokenizer,\n WordpieceTokenizer,\n _is_control,\n _is_punctuation,\n _is_whitespace,\n)\nfrom transformers.testing_utils import (\n is_pt_tf_cross_test,\n require_pandas,\n require_scatter,\n require_tensorflow_probability,\n require_tokenizers,\n require_torch,\n slow,\n)\n\nfrom ...test_tokenization_common import TokenizerTesterMixin, filter_non_english, merge_model_tokenizer_mappings\n\n\n@require_tokenizers\n@require_pandas\nclass TapasTokenizationTest(TokenizerTesterMixin, unittest.TestCase):\n tokenizer_class = TapasTokenizer\n test_rust_tokenizer = False\n space_between_special_tokens = True\n from_pretrained_filter = filter_non_english\n test_seq2seq = False\n\n def get_table(\n self,\n tokenizer: TapasTokenizer,\n length=5,\n ):\n toks = [tokenizer.decode([i], clean_up_tokenization_spaces=False) for i in range(len(tokenizer))]\n\n if length == 0:\n data = {}\n else:\n data = {toks[0]: [toks[tok] for tok in range(1, length)]}\n\n table = pd.DataFrame.from_dict(data)\n\n return table\n\n def get_table_and_query(\n self,\n tokenizer: TapasTokenizer,\n length=5,\n ):\n toks = [tokenizer.decode([i], clean_up_tokenization_spaces=False) for i in range(len(tokenizer))]\n table = self.get_table(tokenizer, length=length - 3)\n query = \" \".join(toks[:3])\n\n return table, query\n\n def get_clean_sequence(\n self,\n tokenizer: TapasTokenizer,\n with_prefix_space=False,\n max_length=20,\n min_length=5,\n empty_table: bool = False,\n add_special_tokens: bool = True,\n return_table_and_query: bool = False,\n ):\n\n toks = [tokenizer.decode([i], clean_up_tokenization_spaces=False) for i in range(len(tokenizer))]\n\n if empty_table:\n table = pd.DataFrame.from_dict({})\n query = \" \".join(toks[:min_length])\n else:\n data = {toks[0]: [toks[tok] for tok in range(1, min_length - 3)]}\n table = pd.DataFrame.from_dict(data)\n query = \" \".join(toks[:3])\n\n output_ids = tokenizer.encode(table, query, add_special_tokens=add_special_tokens)\n output_txt = tokenizer.decode(output_ids)\n\n assert len(output_ids) >= min_length, \"Update the code to generate the sequences so that they are larger\"\n assert len(output_ids) <= max_length, \"Update the code to generate the sequences so that they are smaller\"\n\n if return_table_and_query:\n return output_txt, output_ids, table, query\n\n return output_txt, output_ids\n\n def setUp(self):\n super().setUp()\n\n vocab_tokens = [\n \"[UNK]\",\n \"[CLS]\",\n \"[SEP]\",\n \"[PAD]\",\n \"[MASK]\",\n \"want\",\n \"##want\",\n \"##ed\",\n \"wa\",\n \"un\",\n \"runn\",\n \"##ing\",\n \",\",\n \"low\",\n \"lowest\",\n ]\n self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES[\"vocab_file\"])\n with open(self.vocab_file, \"w\", encoding=\"utf-8\") as vocab_writer:\n vocab_writer.write(\"\".join([x + \"\\n\" for x in vocab_tokens]))\n\n def get_input_output_texts(self, tokenizer):\n input_text = \"UNwant\\u00E9d,running\"\n output_text = \"unwanted, running\"\n return input_text, output_text\n\n @require_tensorflow_probability\n def test_tf_encode_plus_sent_to_model(self):\n super().test_tf_encode_plus_sent_to_model()\n\n def test_rust_and_python_full_tokenizers(self):\n if not self.test_rust_tokenizer:\n return\n\n tokenizer = self.get_tokenizer()\n rust_tokenizer = self.get_rust_tokenizer()\n\n sequence = \"UNwant\\u00E9d,running\"\n\n tokens = tokenizer.tokenize(sequence)\n rust_tokens = rust_tokenizer.tokenize(sequence)\n self.assertListEqual(tokens, rust_tokens)\n\n ids = tokenizer.encode(sequence, add_special_tokens=False)\n rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)\n self.assertListEqual(ids, rust_ids)\n\n rust_tokenizer = self.get_rust_tokenizer()\n ids = tokenizer.encode(sequence)\n rust_ids = rust_tokenizer.encode(sequence)\n self.assertListEqual(ids, rust_ids)\n\n # With lower casing\n tokenizer = self.get_tokenizer(do_lower_case=True)\n rust_tokenizer = self.get_rust_tokenizer(do_lower_case=True)\n\n sequence = \"UNwant\\u00E9d,running\"\n\n tokens = tokenizer.tokenize(sequence)\n rust_tokens = rust_tokenizer.tokenize(sequence)\n self.assertListEqual(tokens, rust_tokens)\n\n ids = tokenizer.encode(sequence, add_special_tokens=False)\n rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)\n self.assertListEqual(ids, rust_ids)\n\n rust_tokenizer = self.get_rust_tokenizer()\n ids = tokenizer.encode(sequence)\n rust_ids = rust_tokenizer.encode(sequence)\n self.assertListEqual(ids, rust_ids)\n\n def test_chinese(self):\n tokenizer = BasicTokenizer()\n\n self.assertListEqual(tokenizer.tokenize(\"ah\\u535A\\u63A8zz\"), [\"ah\", \"\\u535A\", \"\\u63A8\", \"zz\"])\n\n def test_basic_tokenizer_lower(self):\n tokenizer = BasicTokenizer(do_lower_case=True)\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHeLLo!how \\n Are yoU? \"), [\"hello\", \"!\", \"how\", \"are\", \"you\", \"?\"]\n )\n self.assertListEqual(tokenizer.tokenize(\"H\\u00E9llo\"), [\"hello\"])\n\n def test_basic_tokenizer_lower_strip_accents_false(self):\n tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=False)\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHäLLo!how \\n Are yoU? \"), [\"hällo\", \"!\", \"how\", \"are\", \"you\", \"?\"]\n )\n self.assertListEqual(tokenizer.tokenize(\"H\\u00E9llo\"), [\"h\\u00E9llo\"])\n\n def test_basic_tokenizer_lower_strip_accents_true(self):\n tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=True)\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHäLLo!how \\n Are yoU? \"), [\"hallo\", \"!\", \"how\", \"are\", \"you\", \"?\"]\n )\n self.assertListEqual(tokenizer.tokenize(\"H\\u00E9llo\"), [\"hello\"])\n\n def test_basic_tokenizer_lower_strip_accents_default(self):\n tokenizer = BasicTokenizer(do_lower_case=True)\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHäLLo!how \\n Are yoU? \"), [\"hallo\", \"!\", \"how\", \"are\", \"you\", \"?\"]\n )\n self.assertListEqual(tokenizer.tokenize(\"H\\u00E9llo\"), [\"hello\"])\n\n def test_basic_tokenizer_no_lower(self):\n tokenizer = BasicTokenizer(do_lower_case=False)\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHeLLo!how \\n Are yoU? \"), [\"HeLLo\", \"!\", \"how\", \"Are\", \"yoU\", \"?\"]\n )\n\n def test_basic_tokenizer_no_lower_strip_accents_false(self):\n tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=False)\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHäLLo!how \\n Are yoU? \"), [\"HäLLo\", \"!\", \"how\", \"Are\", \"yoU\", \"?\"]\n )\n\n def test_basic_tokenizer_no_lower_strip_accents_true(self):\n tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=True)\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHäLLo!how \\n Are yoU? \"), [\"HaLLo\", \"!\", \"how\", \"Are\", \"yoU\", \"?\"]\n )\n\n def test_basic_tokenizer_respects_never_split_tokens(self):\n tokenizer = BasicTokenizer(do_lower_case=False, never_split=[\"[UNK]\"])\n\n self.assertListEqual(\n tokenizer.tokenize(\" \\tHeLLo!how \\n Are yoU? [UNK]\"), [\"HeLLo\", \"!\", \"how\", \"Are\", \"yoU\", \"?\", \"[UNK]\"]\n )\n\n def test_wordpiece_tokenizer(self):\n vocab_tokens = [\"[UNK]\", \"[CLS]\", \"[SEP]\", \"want\", \"##want\", \"##ed\", \"wa\", \"un\", \"runn\", \"##ing\"]\n\n vocab = {}\n for i, token in enumerate(vocab_tokens):\n vocab[token] = i\n tokenizer = WordpieceTokenizer(vocab=vocab, unk_token=\"[UNK]\")\n\n self.assertListEqual(tokenizer.tokenize(\"\"), [])\n\n self.assertListEqual(tokenizer.tokenize(\"unwanted running\"), [\"un\", \"##want\", \"##ed\", \"runn\", \"##ing\"])\n\n self.assertListEqual(tokenizer.tokenize(\"unwantedX running\"), [\"[UNK]\", \"runn\", \"##ing\"])\n\n def test_is_whitespace(self):\n self.assertTrue(_is_whitespace(\" \"))\n self.assertTrue(_is_whitespace(\"\\t\"))\n self.assertTrue(_is_whitespace(\"\\r\"))\n self.assertTrue(_is_whitespace(\"\\n\"))\n self.assertTrue(_is_whitespace(\"\\u00A0\"))\n\n self.assertFalse(_is_whitespace(\"A\"))\n self.assertFalse(_is_whitespace(\"-\"))\n\n def test_is_control(self):\n self.assertTrue(_is_control(\"\\u0005\"))\n\n self.assertFalse(_is_control(\"A\"))\n self.assertFalse(_is_control(\" \"))\n self.assertFalse(_is_control(\"\\t\"))\n self.assertFalse(_is_control(\"\\r\"))\n\n def test_is_punctuation(self):\n self.assertTrue(_is_punctuation(\"-\"))\n self.assertTrue(_is_punctuation(\"$\"))\n self.assertTrue(_is_punctuation(\"`\"))\n self.assertTrue(_is_punctuation(\".\"))\n\n self.assertFalse(_is_punctuation(\"A\"))\n self.assertFalse(_is_punctuation(\" \"))\n\n def test_clean_text(self):\n tokenizer = self.get_tokenizer()\n\n # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340\n self.assertListEqual(\n [tokenizer.tokenize(t) for t in [\"Test\", \"\\xad\", \"test\"]], [[\"[UNK]\"], [\"[EMPTY]\"], [\"[UNK]\"]]\n )\n\n @slow\n def test_sequence_builders(self):\n tokenizer = self.tokenizer_class.from_pretrained(\"google/tapas-base-finetuned-wtq\")\n\n empty_table = self.get_table(tokenizer, length=0)\n table = self.get_table(tokenizer, length=10)\n\n text = tokenizer.encode(table, add_special_tokens=False)\n text_2 = tokenizer.encode(empty_table, \"multi-sequence build\", add_special_tokens=False)\n\n encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)\n\n assert encoded_pair == [101] + text + [102] + text_2\n\n def test_offsets_with_special_characters(self):\n for tokenizer, pretrained_name, kwargs in self.tokenizers_list:\n with self.subTest(f\"{tokenizer.__class__.__name__} ({pretrained_name})\"):\n tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)\n\n sentence = f\"A, naïve {tokenizer_r.mask_token} AllenNLP sentence.\"\n tokens = tokenizer_r.encode_plus(\n sentence,\n return_attention_mask=False,\n return_token_type_ids=False,\n return_offsets_mapping=True,\n add_special_tokens=True,\n )\n\n do_lower_case = tokenizer_r.do_lower_case if hasattr(tokenizer_r, \"do_lower_case\") else False\n expected_results = (\n [\n ((0, 0), tokenizer_r.cls_token),\n ((0, 1), \"A\"),\n ((1, 2), \",\"),\n ((3, 5), \"na\"),\n ((5, 6), \"##ï\"),\n ((6, 8), \"##ve\"),\n ((9, 15), tokenizer_r.mask_token),\n ((16, 21), \"Allen\"),\n ((21, 23), \"##NL\"),\n ((23, 24), \"##P\"),\n ((25, 33), \"sentence\"),\n ((33, 34), \".\"),\n ((0, 0), tokenizer_r.sep_token),\n ]\n if not do_lower_case\n else [\n ((0, 0), tokenizer_r.cls_token),\n ((0, 1), \"a\"),\n ((1, 2), \",\"),\n ((3, 8), \"naive\"),\n ((9, 15), tokenizer_r.mask_token),\n ((16, 21), \"allen\"),\n ((21, 23), \"##nl\"),\n ((23, 24), \"##p\"),\n ((25, 33), \"sentence\"),\n ((33, 34), \".\"),\n ((0, 0), tokenizer_r.sep_token),\n ]\n )\n\n self.assertEqual(\n [e[1] for e in expected_results], tokenizer_r.convert_ids_to_tokens(tokens[\"input_ids\"])\n )\n self.assertEqual([e[0] for e in expected_results], tokens[\"offset_mapping\"])\n\n def test_add_special_tokens(self):\n tokenizers: List[TapasTokenizer] = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n input_table = self.get_table(tokenizer, length=0)\n\n special_token = \"[SPECIAL_TOKEN]\"\n\n tokenizer.add_special_tokens({\"cls_token\": special_token})\n encoded_special_token = tokenizer.encode(input_table, special_token, add_special_tokens=False)\n self.assertEqual(len(encoded_special_token), 1)\n\n decoded = tokenizer.decode(encoded_special_token, skip_special_tokens=True)\n self.assertTrue(special_token not in decoded)\n\n def test_add_tokens_tokenizer(self):\n tokenizers: List[TapasTokenizer] = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n vocab_size = tokenizer.vocab_size\n all_size = len(tokenizer)\n\n self.assertNotEqual(vocab_size, 0)\n\n # We usually have added tokens from the start in tests because our vocab fixtures are\n # smaller than the original vocabs - let's not assert this\n # self.assertEqual(vocab_size, all_size)\n\n new_toks = [\"aaaaa bbbbbb\", \"cccccccccdddddddd\"]\n added_toks = tokenizer.add_tokens(new_toks)\n vocab_size_2 = tokenizer.vocab_size\n all_size_2 = len(tokenizer)\n\n self.assertNotEqual(vocab_size_2, 0)\n self.assertEqual(vocab_size, vocab_size_2)\n self.assertEqual(added_toks, len(new_toks))\n self.assertEqual(all_size_2, all_size + len(new_toks))\n\n tokens = tokenizer.encode(table, \"aaaaa bbbbbb low cccccccccdddddddd l\", add_special_tokens=False)\n\n self.assertGreaterEqual(len(tokens), 4)\n self.assertGreater(tokens[0], tokenizer.vocab_size - 1)\n self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)\n\n new_toks_2 = {\"eos_token\": \">>>>|||<||<<|<<\", \"pad_token\": \"<<<<<|||>|>>>>|>\"}\n added_toks_2 = tokenizer.add_special_tokens(new_toks_2)\n vocab_size_3 = tokenizer.vocab_size\n all_size_3 = len(tokenizer)\n\n self.assertNotEqual(vocab_size_3, 0)\n self.assertEqual(vocab_size, vocab_size_3)\n self.assertEqual(added_toks_2, len(new_toks_2))\n self.assertEqual(all_size_3, all_size_2 + len(new_toks_2))\n\n tokens = tokenizer.encode(\n table,\n \">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l\",\n add_special_tokens=False,\n )\n\n self.assertGreaterEqual(len(tokens), 6)\n self.assertGreater(tokens[0], tokenizer.vocab_size - 1)\n self.assertGreater(tokens[0], tokens[1])\n self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)\n self.assertGreater(tokens[-2], tokens[-3])\n self.assertEqual(tokens[0], tokenizer.eos_token_id)\n self.assertEqual(tokens[-2], tokenizer.pad_token_id)\n\n @require_tokenizers\n def test_encode_decode_with_spaces(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n\n new_toks = [AddedToken(\"[ABC]\", normalized=False), AddedToken(\"[DEF]\", normalized=False)]\n tokenizer.add_tokens(new_toks)\n input = \"[ABC][DEF][ABC][DEF]\"\n if self.space_between_special_tokens:\n output = \"[ABC] [DEF] [ABC] [DEF]\"\n else:\n output = input\n encoded = tokenizer.encode(table, input, add_special_tokens=False)\n decoded = tokenizer.decode(encoded, spaces_between_special_tokens=self.space_between_special_tokens)\n self.assertIn(decoded, [output, output.lower()])\n\n def test_encode_plus_with_padding(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n sequence = \"Sequence\"\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequence)\n\n padding_size = 10\n padding_idx = tokenizer.pad_token_id\n token_type_padding_idx = tokenizer.pad_token_type_id\n\n encoded_sequence = tokenizer.encode_plus(table, sequence, return_special_tokens_mask=True)\n input_ids = encoded_sequence[\"input_ids\"]\n special_tokens_mask = encoded_sequence[\"special_tokens_mask\"]\n sequence_length = len(input_ids)\n\n # Test 'longest' and 'no_padding' don't do anything\n tokenizer.padding_side = \"right\"\n\n not_padded_sequence = tokenizer.encode_plus(\n table,\n sequence,\n padding=False,\n return_special_tokens_mask=True,\n )\n not_padded_input_ids = not_padded_sequence[\"input_ids\"]\n\n not_padded_special_tokens_mask = not_padded_sequence[\"special_tokens_mask\"]\n not_padded_sequence_length = len(not_padded_input_ids)\n\n assert sequence_length == not_padded_sequence_length\n assert input_ids == not_padded_input_ids\n assert special_tokens_mask == not_padded_special_tokens_mask\n\n not_padded_sequence = tokenizer.encode_plus(\n table,\n sequence,\n padding=False,\n return_special_tokens_mask=True,\n )\n not_padded_input_ids = not_padded_sequence[\"input_ids\"]\n\n not_padded_special_tokens_mask = not_padded_sequence[\"special_tokens_mask\"]\n not_padded_sequence_length = len(not_padded_input_ids)\n\n assert sequence_length == not_padded_sequence_length\n assert input_ids == not_padded_input_ids\n assert special_tokens_mask == not_padded_special_tokens_mask\n\n # Test right padding\n tokenizer.padding_side = \"right\"\n\n right_padded_sequence = tokenizer.encode_plus(\n table,\n sequence,\n max_length=sequence_length + padding_size,\n padding=\"max_length\",\n return_special_tokens_mask=True,\n )\n right_padded_input_ids = right_padded_sequence[\"input_ids\"]\n\n right_padded_special_tokens_mask = right_padded_sequence[\"special_tokens_mask\"]\n right_padded_sequence_length = len(right_padded_input_ids)\n\n assert sequence_length + padding_size == right_padded_sequence_length\n assert input_ids + [padding_idx] * padding_size == right_padded_input_ids\n assert special_tokens_mask + [1] * padding_size == right_padded_special_tokens_mask\n\n # Test left padding\n tokenizer.padding_side = \"left\"\n left_padded_sequence = tokenizer.encode_plus(\n table,\n sequence,\n max_length=sequence_length + padding_size,\n padding=\"max_length\",\n return_special_tokens_mask=True,\n )\n left_padded_input_ids = left_padded_sequence[\"input_ids\"]\n left_padded_special_tokens_mask = left_padded_sequence[\"special_tokens_mask\"]\n left_padded_sequence_length = len(left_padded_input_ids)\n\n assert sequence_length + padding_size == left_padded_sequence_length\n assert [padding_idx] * padding_size + input_ids == left_padded_input_ids\n assert [1] * padding_size + special_tokens_mask == left_padded_special_tokens_mask\n\n if \"token_type_ids\" in tokenizer.model_input_names:\n token_type_ids = encoded_sequence[\"token_type_ids\"]\n left_padded_token_type_ids = left_padded_sequence[\"token_type_ids\"]\n right_padded_token_type_ids = right_padded_sequence[\"token_type_ids\"]\n\n assert (\n token_type_ids + [[token_type_padding_idx] * 7] * padding_size == right_padded_token_type_ids\n )\n assert [[token_type_padding_idx] * 7] * padding_size + token_type_ids == left_padded_token_type_ids\n\n if \"attention_mask\" in tokenizer.model_input_names:\n attention_mask = encoded_sequence[\"attention_mask\"]\n right_padded_attention_mask = right_padded_sequence[\"attention_mask\"]\n left_padded_attention_mask = left_padded_sequence[\"attention_mask\"]\n\n assert attention_mask + [0] * padding_size == right_padded_attention_mask\n assert [0] * padding_size + attention_mask == left_padded_attention_mask\n\n def test_internal_consistency(self):\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n input_text, output_text = self.get_input_output_texts(tokenizer)\n\n tokens = tokenizer.tokenize(input_text)\n ids = tokenizer.convert_tokens_to_ids(tokens)\n ids_2 = tokenizer.encode(table, input_text, add_special_tokens=False)\n self.assertListEqual(ids, ids_2)\n\n tokens_2 = tokenizer.convert_ids_to_tokens(ids)\n self.assertNotEqual(len(tokens_2), 0)\n text_2 = tokenizer.decode(ids)\n self.assertIsInstance(text_2, str)\n\n self.assertEqual(text_2, output_text)\n\n def test_mask_output(self):\n tokenizers = self.get_tokenizers(fast=False, do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table, query = self.get_table_and_query(tokenizer)\n\n if (\n tokenizer.build_inputs_with_special_tokens.__qualname__.split(\".\")[0] != \"PreTrainedTokenizer\"\n and \"token_type_ids\" in tokenizer.model_input_names\n ):\n information = tokenizer.encode_plus(table, query, add_special_tokens=True)\n sequences, mask = information[\"input_ids\"], information[\"token_type_ids\"]\n self.assertEqual(len(sequences), len(mask))\n\n @unittest.skip(\"TAPAS tokenizer only handles two sequences.\")\n def test_maximum_encoding_length_pair_input(self):\n pass\n\n @unittest.skip(\"TAPAS tokenizer only handles two sequences.\")\n def test_maximum_encoding_length_single_input(self):\n pass\n\n def test_number_of_added_tokens(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n\n table, query = self.get_table_and_query(tokenizer)\n\n sequences = tokenizer.encode(table, query, add_special_tokens=False)\n attached_sequences = tokenizer.encode(table, query, add_special_tokens=True)\n\n # Method is implemented (e.g. not GPT-2)\n if len(attached_sequences) != 2:\n self.assertEqual(\n tokenizer.num_special_tokens_to_add(pair=True), len(attached_sequences) - len(sequences)\n )\n\n def test_padding_to_max_length(self):\n \"\"\"We keep this test for backward compatibility but it should be removed when `pad_to_max_length` will be deprecated\"\"\"\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer)\n sequence = \"Sequence\"\n padding_size = 10\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequence)\n\n padding_idx = tokenizer.pad_token_id\n\n # Check that it correctly pads when a maximum length is specified along with the padding flag set to True\n tokenizer.padding_side = \"right\"\n encoded_sequence = tokenizer.encode(table, sequence)\n sequence_length = len(encoded_sequence)\n # FIXME: the next line should be padding(max_length) to avoid warning\n padded_sequence = tokenizer.encode(\n table, sequence, max_length=sequence_length + padding_size, padding=True\n )\n padded_sequence_length = len(padded_sequence)\n assert sequence_length + padding_size == padded_sequence_length\n assert encoded_sequence + [padding_idx] * padding_size == padded_sequence\n\n # Check that nothing is done when a maximum length is not specified\n encoded_sequence = tokenizer.encode(table, sequence)\n sequence_length = len(encoded_sequence)\n\n tokenizer.padding_side = \"right\"\n padded_sequence_right = tokenizer.encode(table, sequence, pad_to_max_length=True)\n padded_sequence_right_length = len(padded_sequence_right)\n assert sequence_length == padded_sequence_right_length\n assert encoded_sequence == padded_sequence_right\n\n def test_call(self):\n # Tests that all call wrap to encode_plus and batch_encode_plus\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n # Test not batched\n table = self.get_table(tokenizer, length=0)\n encoded_sequences_1 = tokenizer.encode_plus(table, sequences[0])\n encoded_sequences_2 = tokenizer(table, sequences[0])\n self.assertEqual(encoded_sequences_1, encoded_sequences_2)\n\n # Test not batched pairs\n table = self.get_table(tokenizer, length=10)\n encoded_sequences_1 = tokenizer.encode_plus(table, sequences[1])\n encoded_sequences_2 = tokenizer(table, sequences[1])\n self.assertEqual(encoded_sequences_1, encoded_sequences_2)\n\n # Test batched\n table = self.get_table(tokenizer, length=0)\n encoded_sequences_1 = tokenizer.batch_encode_plus(table, sequences)\n encoded_sequences_2 = tokenizer(table, sequences)\n self.assertEqual(encoded_sequences_1, encoded_sequences_2)\n\n def test_batch_encode_plus_batch_sequence_length(self):\n # Tests that all encoded values have the correct size\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n encoded_sequences = [tokenizer.encode_plus(table, sequence) for sequence in sequences]\n encoded_sequences_batch = tokenizer.batch_encode_plus(table, sequences, padding=False)\n self.assertListEqual(\n encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)\n )\n\n maximum_length = len(\n max([encoded_sequence[\"input_ids\"] for encoded_sequence in encoded_sequences], key=len)\n )\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequences)\n\n encoded_sequences_padded = [\n tokenizer.encode_plus(table, sequence, max_length=maximum_length, padding=\"max_length\")\n for sequence in sequences\n ]\n\n encoded_sequences_batch_padded = tokenizer.batch_encode_plus(table, sequences, padding=True)\n self.assertListEqual(\n encoded_sequences_padded,\n self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch_padded),\n )\n\n # check 'longest' is unsensitive to a max length\n encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(table, sequences, padding=True)\n encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus(\n table, sequences, max_length=maximum_length + 10, padding=\"longest\"\n )\n for key in encoded_sequences_batch_padded_1.keys():\n self.assertListEqual(\n encoded_sequences_batch_padded_1[key],\n encoded_sequences_batch_padded_2[key],\n )\n\n # check 'no_padding' is unsensitive to a max length\n encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(table, sequences, padding=False)\n encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus(\n table, sequences, max_length=maximum_length + 10, padding=False\n )\n for key in encoded_sequences_batch_padded_1.keys():\n self.assertListEqual(\n encoded_sequences_batch_padded_1[key],\n encoded_sequences_batch_padded_2[key],\n )\n\n @unittest.skip(\"batch_encode_plus does not handle overflowing tokens.\")\n def test_batch_encode_plus_overflowing_tokens(self):\n pass\n\n def test_batch_encode_plus_padding(self):\n # Test that padded sequences are equivalent between batch_encode_plus and encode_plus\n\n # Right padding tests\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n max_length = 100\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequences)\n\n encoded_sequences = [\n tokenizer.encode_plus(table, sequence, max_length=max_length, padding=\"max_length\")\n for sequence in sequences\n ]\n encoded_sequences_batch = tokenizer.batch_encode_plus(\n table, sequences, max_length=max_length, padding=\"max_length\"\n )\n self.assertListEqual(\n encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)\n )\n\n # Left padding tests\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n tokenizer.padding_side = \"left\"\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n max_length = 100\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequences)\n\n encoded_sequences = [\n tokenizer.encode_plus(table, sequence, max_length=max_length, padding=\"max_length\")\n for sequence in sequences\n ]\n encoded_sequences_batch = tokenizer.batch_encode_plus(\n table, sequences, max_length=max_length, padding=\"max_length\"\n )\n self.assertListEqual(\n encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)\n )\n\n def test_padding_to_multiple_of(self):\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n if tokenizer.pad_token is None:\n self.skipTest(\"No padding token.\")\n else:\n empty_tokens = tokenizer(table, padding=True, pad_to_multiple_of=8)\n normal_tokens = tokenizer(table, \"This is a sample input\", padding=True, pad_to_multiple_of=8)\n for key, value in empty_tokens.items():\n self.assertEqual(len(value) % 8, 0, f\"BatchEncoding.{key} is not multiple of 8\")\n for key, value in normal_tokens.items():\n self.assertEqual(len(value) % 8, 0, f\"BatchEncoding.{key} is not multiple of 8\")\n\n normal_tokens = tokenizer(table, \"This\", pad_to_multiple_of=8)\n for key, value in normal_tokens.items():\n self.assertNotEqual(len(value) % 8, 0, f\"BatchEncoding.{key} is not multiple of 8\")\n\n # Should also work with truncation\n normal_tokens = tokenizer(table, \"This\", padding=True, truncation=True, pad_to_multiple_of=8)\n for key, value in normal_tokens.items():\n self.assertEqual(len(value) % 8, 0, f\"BatchEncoding.{key} is not multiple of 8\")\n\n @unittest.skip(\"TAPAS cannot handle `prepare_for_model` without passing by `encode_plus` or `batch_encode_plus`\")\n def test_prepare_for_model(self):\n pass\n\n def test_tokenizer_slow_store_full_signature(self):\n signature = inspect.signature(self.tokenizer_class.__init__)\n tokenizer = self.get_tokenizer()\n\n for parameter_name, parameter in signature.parameters.items():\n if parameter.default != inspect.Parameter.empty:\n self.assertIn(parameter_name, tokenizer.init_kwargs)\n\n def test_special_tokens_mask_input_pairs(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequence_0 = \"Encode this.\"\n empty_table = self.get_table(tokenizer, length=0)\n table = self.get_table(tokenizer, length=10)\n encoded_sequence = tokenizer.encode(empty_table, sequence_0, add_special_tokens=False)\n encoded_sequence += tokenizer.encode(table, \"\", add_special_tokens=False)\n encoded_sequence_dict = tokenizer.encode_plus(\n table,\n sequence_0,\n add_special_tokens=True,\n return_special_tokens_mask=True,\n # add_prefix_space=False,\n )\n encoded_sequence_w_special = encoded_sequence_dict[\"input_ids\"]\n special_tokens_mask = encoded_sequence_dict[\"special_tokens_mask\"]\n self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special))\n\n filtered_sequence = [\n (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special)\n ]\n filtered_sequence = [x for x in filtered_sequence if x is not None]\n self.assertEqual(encoded_sequence, filtered_sequence)\n\n def test_special_tokens_mask(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n sequence_0 = \"Encode this.\"\n # Testing single inputs\n encoded_sequence = tokenizer.encode(table, sequence_0, add_special_tokens=False)\n encoded_sequence_dict = tokenizer.encode_plus(\n table, sequence_0, add_special_tokens=True, return_special_tokens_mask=True\n )\n encoded_sequence_w_special = encoded_sequence_dict[\"input_ids\"]\n special_tokens_mask = encoded_sequence_dict[\"special_tokens_mask\"]\n self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special))\n\n filtered_sequence = [x for i, x in enumerate(encoded_sequence_w_special) if not special_tokens_mask[i]]\n self.assertEqual(encoded_sequence, filtered_sequence)\n\n def test_save_and_load_tokenizer(self):\n # safety check on max_len default value so we are sure the test works\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n self.assertNotEqual(tokenizer.model_max_length, 42)\n\n # Now let's start the test\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n # Isolate this from the other tests because we save additional tokens/etc\n table = self.get_table(tokenizer, length=0)\n tmpdirname = tempfile.mkdtemp()\n\n sample_text = \" He is very happy, UNwant\\u00E9d,running\"\n before_tokens = tokenizer.encode(table, sample_text, add_special_tokens=False)\n before_vocab = tokenizer.get_vocab()\n tokenizer.save_pretrained(tmpdirname)\n\n after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)\n after_tokens = after_tokenizer.encode(table, sample_text, add_special_tokens=False)\n after_vocab = after_tokenizer.get_vocab()\n self.assertListEqual(before_tokens, after_tokens)\n self.assertDictEqual(before_vocab, after_vocab)\n\n shutil.rmtree(tmpdirname)\n\n @unittest.skip(\"Not implemented\")\n def test_right_and_left_truncation(self):\n pass\n\n def test_right_and_left_padding(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n table = self.get_table(tokenizer, length=0)\n sequence = \"Sequence\"\n padding_size = 10\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequence)\n\n padding_idx = tokenizer.pad_token_id\n\n # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True\n tokenizer.padding_side = \"right\"\n encoded_sequence = tokenizer.encode(table, sequence)\n sequence_length = len(encoded_sequence)\n padded_sequence = tokenizer.encode(\n table, sequence, max_length=sequence_length + padding_size, padding=\"max_length\"\n )\n padded_sequence_length = len(padded_sequence)\n assert sequence_length + padding_size == padded_sequence_length\n assert encoded_sequence + [padding_idx] * padding_size == padded_sequence\n\n # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True\n tokenizer.padding_side = \"left\"\n encoded_sequence = tokenizer.encode(table, sequence)\n sequence_length = len(encoded_sequence)\n padded_sequence = tokenizer.encode(\n table, sequence, max_length=sequence_length + padding_size, padding=\"max_length\"\n )\n padded_sequence_length = len(padded_sequence)\n assert sequence_length + padding_size == padded_sequence_length\n assert [padding_idx] * padding_size + encoded_sequence == padded_sequence\n\n # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding'\n encoded_sequence = tokenizer.encode(table, sequence)\n sequence_length = len(encoded_sequence)\n\n tokenizer.padding_side = \"right\"\n padded_sequence_right = tokenizer.encode(table, sequence, padding=True)\n padded_sequence_right_length = len(padded_sequence_right)\n assert sequence_length == padded_sequence_right_length\n assert encoded_sequence == padded_sequence_right\n\n tokenizer.padding_side = \"left\"\n padded_sequence_left = tokenizer.encode(table, sequence, padding=\"longest\")\n padded_sequence_left_length = len(padded_sequence_left)\n assert sequence_length == padded_sequence_left_length\n assert encoded_sequence == padded_sequence_left\n\n tokenizer.padding_side = \"right\"\n padded_sequence_right = tokenizer.encode(table, sequence)\n padded_sequence_right_length = len(padded_sequence_right)\n assert sequence_length == padded_sequence_right_length\n assert encoded_sequence == padded_sequence_right\n\n tokenizer.padding_side = \"left\"\n padded_sequence_left = tokenizer.encode(table, sequence, padding=False)\n padded_sequence_left_length = len(padded_sequence_left)\n assert sequence_length == padded_sequence_left_length\n assert encoded_sequence == padded_sequence_left\n\n def test_token_type_ids(self):\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n empty_table = self.get_table(tokenizer, length=0)\n seq_0 = \"Test this method.\"\n\n # We want to have sequence 0 and sequence 1 are tagged\n # respectively with 0 and 1 token_ids\n # (regardless of whether the model use token type ids)\n # We use this assumption in the QA pipeline among other place\n output = tokenizer(empty_table, seq_0, return_token_type_ids=True)\n\n # Assert that the token type IDs have the same length as the input IDs\n self.assertEqual(len(output[\"token_type_ids\"]), len(output[\"input_ids\"]))\n\n # Assert that each token type ID has 7 values\n self.assertTrue(all(len(token_type_ids) == 7 for token_type_ids in output[\"token_type_ids\"]))\n\n # Do the same test as modeling common.\n self.assertIn(0, output[\"token_type_ids\"][0])\n\n @require_torch\n @slow\n @require_scatter\n def test_torch_encode_plus_sent_to_model(self):\n import torch\n\n from transformers import MODEL_MAPPING, TOKENIZER_MAPPING\n\n MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING)\n\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n\n if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING:\n return\n\n config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__]\n config = config_class()\n\n if config.is_encoder_decoder or config.pad_token_id is None:\n return\n\n model = model_class(config)\n\n # Make sure the model contains at least the full vocabulary size in its embedding matrix\n is_using_common_embeddings = hasattr(model.get_input_embeddings(), \"weight\")\n assert (\n (model.get_input_embeddings().weight.shape[0] >= len(tokenizer))\n if is_using_common_embeddings\n else True\n )\n\n # Build sequence\n first_ten_tokens = list(tokenizer.get_vocab().keys())[:10]\n sequence = \" \".join(first_ten_tokens)\n table = self.get_table(tokenizer, length=0)\n encoded_sequence = tokenizer.encode_plus(table, sequence, return_tensors=\"pt\")\n batch_encoded_sequence = tokenizer.batch_encode_plus(table, [sequence, sequence], return_tensors=\"pt\")\n # This should not fail\n\n with torch.no_grad(): # saves some time\n model(**encoded_sequence)\n model(**batch_encoded_sequence)\n\n @unittest.skip(\"TAPAS doesn't handle pre-tokenized inputs.\")\n def test_pretokenized_inputs(self):\n pass\n\n @slow\n def test_tapas_truncation_integration_test(self):\n data = {\n \"Actors\": [\"Brad Pitt\", \"Leonardo Di Caprio\", \"George Clooney\"],\n \"Age\": [\"56\", \"45\", \"59\"],\n \"Number of movies\": [\"87\", \"53\", \"69\"],\n \"Date of birth\": [\"18 december 1963\", \"11 november 1974\", \"6 may 1961\"],\n }\n queries = [\n \"When was Brad Pitt born?\",\n \"Which actor appeared in the least number of movies?\",\n \"What is the average number of movies?\",\n ]\n table = pd.DataFrame.from_dict(data)\n\n tokenizer = TapasTokenizer.from_pretrained(\"lysandre/tapas-temporary-repo\", model_max_length=512)\n\n for i in range(12):\n # The table cannot even encode the headers, so raise an error\n with self.assertRaises(ValueError):\n tokenizer.encode(table=table, query=queries[0], max_length=i, truncation=\"drop_rows_to_fit\")\n\n for i in range(12, 512):\n new_encoded_inputs = tokenizer.encode(\n table=table, query=queries[0], max_length=i, truncation=\"drop_rows_to_fit\"\n )\n\n # Ensure that the input IDs are less than the max length defined.\n self.assertLessEqual(len(new_encoded_inputs), i)\n\n tokenizer.model_max_length = 20\n new_encoded_inputs = tokenizer.encode(table=table, query=queries[0], truncation=True)\n dropped_encoded_inputs = tokenizer.encode(table=table, query=queries[0], truncation=\"drop_rows_to_fit\")\n\n # Ensure that the input IDs are still truncated when no max_length is specified\n self.assertListEqual(new_encoded_inputs, dropped_encoded_inputs)\n self.assertLessEqual(len(new_encoded_inputs), 20)\n\n @slow\n def test_min_max_question_length(self):\n data = {\n \"Actors\": [\"Brad Pitt\", \"Leonardo Di Caprio\", \"George Clooney\"],\n \"Age\": [\"56\", \"45\", \"59\"],\n \"Number of movies\": [\"87\", \"53\", \"69\"],\n \"Date of birth\": [\"18 december 1963\", \"11 november 1974\", \"6 may 1961\"],\n }\n queries = \"When was Brad Pitt born?\"\n table = pd.DataFrame.from_dict(data)\n\n # test max_question_length\n tokenizer = TapasTokenizer.from_pretrained(\"lysandre/tapas-temporary-repo\", max_question_length=2)\n\n encoding = tokenizer(table=table, queries=queries)\n\n # query should not be tokenized as it's longer than the specified max_question_length\n expected_results = [101, 102]\n\n self.assertListEqual(encoding.input_ids[:2], expected_results)\n\n # test min_question_length\n tokenizer = TapasTokenizer.from_pretrained(\"lysandre/tapas-temporary-repo\", min_question_length=30)\n\n encoding = tokenizer(table=table, queries=queries)\n\n # query should not be tokenized as it's shorter than the specified min_question_length\n expected_results = [101, 102]\n\n self.assertListEqual(encoding.input_ids[:2], expected_results)\n\n @is_pt_tf_cross_test\n def test_batch_encode_plus_tensors(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n table = self.get_table(tokenizer, length=0)\n\n # A Tensor cannot be build by sequences which are not the same size\n self.assertRaises(ValueError, tokenizer.batch_encode_plus, table, sequences, return_tensors=\"pt\")\n self.assertRaises(ValueError, tokenizer.batch_encode_plus, table, sequences, return_tensors=\"tf\")\n\n if tokenizer.pad_token_id is None:\n self.assertRaises(\n ValueError,\n tokenizer.batch_encode_plus,\n table,\n sequences,\n padding=True,\n return_tensors=\"pt\",\n )\n self.assertRaises(\n ValueError,\n tokenizer.batch_encode_plus,\n table,\n sequences,\n padding=\"longest\",\n return_tensors=\"tf\",\n )\n else:\n pytorch_tensor = tokenizer.batch_encode_plus(table, sequences, padding=True, return_tensors=\"pt\")\n tensorflow_tensor = tokenizer.batch_encode_plus(\n table, sequences, padding=\"longest\", return_tensors=\"tf\"\n )\n encoded_sequences = tokenizer.batch_encode_plus(table, sequences, padding=True)\n\n for key in encoded_sequences.keys():\n pytorch_value = pytorch_tensor[key].tolist()\n tensorflow_value = tensorflow_tensor[key].numpy().tolist()\n encoded_value = encoded_sequences[key]\n\n self.assertEqual(pytorch_value, tensorflow_value, encoded_value)\n\n @slow\n def test_tapas_integration_test(self):\n data = {\n \"Actors\": [\"Brad Pitt\", \"Leonardo Di Caprio\", \"George Clooney\"],\n \"Age\": [\"56\", \"45\", \"59\"],\n \"Number of movies\": [\"87\", \"53\", \"69\"],\n \"Date of birth\": [\"18 december 1963\", \"11 november 1974\", \"6 may 1961\"],\n }\n queries = [\n \"When was Brad Pitt born?\",\n \"Which actor appeared in the least number of movies?\",\n \"What is the average number of movies?\",\n ]\n table = pd.DataFrame.from_dict(data)\n\n tokenizer = TapasTokenizer.from_pretrained(\"google/tapas-base-finetuned-wtq\", model_max_length=512)\n\n # fmt: off\n expected_results = {'input_ids':[101,2043,2001,8226,15091,2141,1029,102,5889,2287,2193,1997,5691,3058,1997,4182,8226,15091,5179,6584,2324,2285,3699,14720,4487,6178,9488,3429,5187,2340,2281,3326,2577,18856,7828,3240,5354,6353,1020,2089,3777],'attention_mask':[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,1,1,1],'token_type_ids':[[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,0,0,0,0],[1,1,0,0,0,0,0],[1,2,0,0,0,0,0],[1,3,0,0,0,0,0],[1,3,0,0,0,0,0],[1,3,0,0,0,0,0],[1,4,0,0,0,0,0],[1,4,0,0,0,0,0],[1,4,0,0,0,0,0],[1,1,1,0,0,0,0],[1,1,1,0,0,0,0],[1,2,1,0,2,2,0],[1,3,1,0,3,1,0],[1,4,1,0,2,2,0],[1,4,1,0,2,2,0],[1,4,1,0,2,2,0],[1,1,2,0,0,0,0],[1,1,2,0,0,0,0],[1,1,2,0,0,0,0],[1,1,2,0,0,0,0],[1,2,2,0,1,3,0],[1,3,2,0,1,3,0],[1,4,2,0,3,1,0],[1,4,2,0,3,1,0],[1,4,2,0,3,1,0],[1,1,3,0,0,0,0],[1,1,3,0,0,0,0],[1,1,3,0,0,0,0],[1,1,3,0,0,0,0],[1,2,3,0,3,1,0],[1,3,3,0,2,2,0],[1,4,3,0,1,3,0],[1,4,3,0,1,3,0],[1,4,3,0,1,3,0]]} # noqa: E231\n # fmt: on\n\n new_encoded_inputs = tokenizer.encode_plus(table=table, query=queries[0])\n\n self.assertDictEqual(dict(new_encoded_inputs), expected_results)\n\n @slow\n def test_full_tokenizer(self):\n data = [\n [\"Pos\", \"No\", \"Driver\", \"Team\", \"Laps\", \"Time/Retired\", \"Grid\", \"Points\"],\n [\"1\", \"32\", \"Patrick Carpentier\", \"Team Player's\", \"87\", \"1:48:11.023\", \"1\", \"22\"],\n [\"2\", \"1\", \"Bruno Junqueira\", \"Newman/Haas Racing\", \"87\", \"+0.8 secs\", \"2\", \"17\"],\n [\"3\", \"3\", \"Paul Tracy\", \"Team Player's\", \"87\", \"+28.6 secs\", \"3\", \"14\"],\n [\"4\", \"9\", \"Michel Jourdain, Jr.\", \"Team Rahal\", \"87\", \"+40.8 secs\", \"13\", \"12\"],\n [\"5\", \"34\", \"Mario Haberfeld\", \"Mi-Jack Conquest Racing\", \"87\", \"+42.1 secs\", \"6\", \"10\"],\n [\"6\", \"20\", \"Oriol Servia\", \"Patrick Racing\", \"87\", \"+1:00.2\", \"10\", \"8\"],\n [\"7\", \"51\", \"Adrian Fernandez\", \"Fernandez Racing\", \"87\", \"+1:01.4\", \"5\", \"6\"],\n [\"8\", \"12\", \"Jimmy Vasser\", \"American Spirit Team Johansson\", \"87\", \"+1:01.8\", \"8\", \"5\"],\n [\"9\", \"7\", \"Tiago Monteiro\", \"Fittipaldi-Dingman Racing\", \"86\", \"+ 1 Lap\", \"15\", \"4\"],\n [\"10\", \"55\", \"Mario Dominguez\", \"Herdez Competition\", \"86\", \"+ 1 Lap\", \"11\", \"3\"],\n [\"11\", \"27\", \"Bryan Herta\", \"PK Racing\", \"86\", \"+ 1 Lap\", \"12\", \"2\"],\n [\"12\", \"31\", \"Ryan Hunter-Reay\", \"American Spirit Team Johansson\", \"86\", \"+ 1 Lap\", \"17\", \"1\"],\n [\"13\", \"19\", \"Joel Camathias\", \"Dale Coyne Racing\", \"85\", \"+ 2 Laps\", \"18\", \"0\"],\n [\"14\", \"33\", \"Alex Tagliani\", \"Rocketsports Racing\", \"85\", \"+ 2 Laps\", \"14\", \"0\"],\n [\"15\", \"4\", \"Roberto Moreno\", \"Herdez Competition\", \"85\", \"+ 2 Laps\", \"9\", \"0\"],\n [\"16\", \"11\", \"Geoff Boss\", \"Dale Coyne Racing\", \"83\", \"Mechanical\", \"19\", \"0\"],\n [\"17\", \"2\", \"Sebastien Bourdais\", \"Newman/Haas Racing\", \"77\", \"Mechanical\", \"4\", \"0\"],\n [\"18\", \"15\", \"Darren Manning\", \"Walker Racing\", \"12\", \"Mechanical\", \"7\", \"0\"],\n [\"19\", \"5\", \"Rodolfo Lavin\", \"Walker Racing\", \"10\", \"Mechanical\", \"16\", \"0\"],\n ]\n query = \"what were the drivers names?\"\n table = pd.DataFrame.from_records(data[1:], columns=data[0])\n\n tokenizer = TapasTokenizer.from_pretrained(\"google/tapas-base-finetuned-wtq\", model_max_length=512)\n model_inputs = tokenizer(table, query, padding=\"max_length\")\n\n input_ids = model_inputs[\"input_ids\"]\n token_type_ids = np.array(model_inputs[\"token_type_ids\"])\n segment_ids = token_type_ids[:, 0]\n column_ids = token_type_ids[:, 1]\n row_ids = token_type_ids[:, 2]\n\n # fmt: off\n expected_results = {'input_ids':[101,2054,2020,1996,6853,3415,1029,102,13433,2015,2053,4062,2136,10876,2051,1013,3394,8370,2685,1015,3590,4754,29267,4765,3771,2136,2447,1005,1055,6584,1015,1024,4466,1024,2340,1012,6185,2509,1015,2570,1016,1015,10391,12022,4226,7895,10625,1013,22996,3868,6584,1009,1014,1012,1022,10819,2015,1016,2459,1017,1017,2703,10555,2136,2447,1005,1055,6584,1009,2654,1012,1020,10819,2015,1017,2403,1018,1023,8709,8183,3126,21351,2078,1010,3781,1012,2136,10958,8865,6584,1009,2871,1012,1022,10819,2015,2410,2260,1019,4090,7986,5292,5677,8151,2771,1011,2990,9187,3868,6584,1009,4413,1012,1015,10819,2015,1020,2184,1020,2322,2030,20282,14262,9035,4754,3868,6584,1009,1015,1024,4002,1012,1016,2184,1022,1021,4868,7918,12023,12023,3868,6584,1009,1015,1024,5890,1012,1018,1019,1020,1022,2260,5261,12436,18116,2137,4382,2136,26447,6584,1009,1015,1024,5890,1012,1022,1022,1019,1023,1021,27339,3995,10125,9711,4906,25101,24657,1011,22033,2386,3868,6564,1009,1015,5001,2321,1018,2184,4583,7986,14383,2075,29488,14906,9351,2971,6564,1009,1015,5001,2340,1017,2340,2676,8527,2014,2696,1052,2243,3868,6564,1009,1015,5001,2260,1016,2260,2861,4575,4477,1011,2128,4710,2137,4382,2136,26447,6564,1009,1015,5001,2459,1015,2410,2539,8963,11503,25457,3022,8512,2522,9654,3868,5594,1009,1016,10876,2324,1014,2403,3943,4074,6415,15204,2072,12496,25378,3868,5594,1009,1016,10876,2403,1014,2321,1018,10704,17921,14906,9351,2971,5594,1009,1016,10876,1023,1014,2385,2340,14915,5795,8512,2522,9654,3868,6640,6228,2539,1014,2459,1016,28328,8945,3126,21351,2015,10625,1013,22996,3868,6255,6228,1018,1014,2324,2321,12270,11956,5232,3868,2260,6228,1021,1014,2539,1019,8473,28027,2080,2474,6371,5232,3868,2184,6228,2385,1014,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,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,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,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],'column_ids':[0,0,0,0,0,0,0,0,1,1,2,3,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,5,6,6,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,3,3,3,3,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,3,4,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,4,4,4,4,5,6,7,8,1,2,3,3,3,3,3,4,4,4,4,5,6,7,8,1,2,3,3,4,4,5,6,7,8,1,2,3,3,3,3,3,4,4,5,6,7,8,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,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,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,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],'row_ids':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,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,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,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,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],'segment_ids':[0,0,0,0,0,0,0,0,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,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,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,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,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,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,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,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,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]} # noqa: E231\n # fmt: on\n\n self.assertListEqual(input_ids, expected_results[\"input_ids\"])\n self.assertListEqual(segment_ids.tolist(), expected_results[\"segment_ids\"])\n self.assertListEqual(column_ids.tolist(), expected_results[\"column_ids\"])\n self.assertListEqual(row_ids.tolist(), expected_results[\"row_ids\"])\n\n @unittest.skip(\"Skip this test while all models are still to be uploaded.\")\n def test_pretrained_model_lists(self):\n pass\n\n @unittest.skip(\"Doesn't support another framework than PyTorch\")\n def test_np_encode_plus_sent_to_model(self):\n pass\n", "# coding=utf-8\n# Copyright 2021 The HuggingFace Inc. team. 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\"\"\" Testing suite for the PyTorch BigBird model. \"\"\"\n\n\nimport unittest\n\nfrom transformers import BigBirdConfig, is_torch_available\nfrom transformers.models.auto import get_values\nfrom transformers.models.big_bird.tokenization_big_bird import BigBirdTokenizer\nfrom transformers.testing_utils import require_torch, slow, torch_device\n\nfrom ...test_configuration_common import ConfigTester\nfrom ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask\n\n\nif is_torch_available():\n import torch\n\n from transformers import (\n MODEL_FOR_PRETRAINING_MAPPING,\n BigBirdForCausalLM,\n BigBirdForMaskedLM,\n BigBirdForMultipleChoice,\n BigBirdForPreTraining,\n BigBirdForQuestionAnswering,\n BigBirdForSequenceClassification,\n BigBirdForTokenClassification,\n BigBirdModel,\n )\n from transformers.models.big_bird.modeling_big_bird import BIG_BIRD_PRETRAINED_MODEL_ARCHIVE_LIST\n\n\nclass BigBirdModelTester:\n def __init__(\n self,\n parent,\n batch_size=7,\n seq_length=128,\n is_training=True,\n use_input_mask=True,\n use_token_type_ids=True,\n use_labels=True,\n vocab_size=99,\n hidden_size=32,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=37,\n hidden_act=\"gelu_new\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=256,\n type_vocab_size=16,\n type_sequence_label_size=2,\n initializer_range=0.02,\n num_labels=3,\n num_choices=4,\n attention_type=\"block_sparse\",\n use_bias=True,\n rescale_embeddings=False,\n block_size=8,\n num_rand_blocks=3,\n position_embedding_type=\"absolute\",\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_input_mask = use_input_mask\n self.use_token_type_ids = use_token_type_ids\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.type_sequence_label_size = type_sequence_label_size\n self.initializer_range = initializer_range\n self.num_labels = num_labels\n self.num_choices = num_choices\n self.scope = scope\n\n self.attention_type = attention_type\n self.use_bias = use_bias\n self.rescale_embeddings = rescale_embeddings\n self.block_size = block_size\n self.num_rand_blocks = num_rand_blocks\n self.position_embedding_type = position_embedding_type\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n\n input_mask = None\n if self.use_input_mask:\n input_mask = random_attention_mask([self.batch_size, self.seq_length])\n\n token_type_ids = None\n if self.use_token_type_ids:\n token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)\n\n sequence_labels = None\n token_labels = None\n choice_labels = None\n if self.use_labels:\n sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)\n token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)\n choice_labels = ids_tensor([self.batch_size], self.num_choices)\n\n config = self.get_config()\n\n return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n\n def get_config(self):\n return BigBirdConfig(\n vocab_size=self.vocab_size,\n hidden_size=self.hidden_size,\n num_hidden_layers=self.num_hidden_layers,\n num_attention_heads=self.num_attention_heads,\n intermediate_size=self.intermediate_size,\n hidden_act=self.hidden_act,\n hidden_dropout_prob=self.hidden_dropout_prob,\n attention_probs_dropout_prob=self.attention_probs_dropout_prob,\n max_position_embeddings=self.max_position_embeddings,\n type_vocab_size=self.type_vocab_size,\n is_encoder_decoder=False,\n initializer_range=self.initializer_range,\n attention_type=self.attention_type,\n use_bias=self.use_bias,\n rescale_embeddings=self.rescale_embeddings,\n block_size=self.block_size,\n num_random_blocks=self.num_rand_blocks,\n position_embedding_type=self.position_embedding_type,\n )\n\n def prepare_config_and_inputs_for_decoder(self):\n (\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n ) = self.prepare_config_and_inputs()\n\n config.is_decoder = True\n encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])\n encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)\n\n return (\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n encoder_hidden_states,\n encoder_attention_mask,\n )\n\n def create_and_check_model(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n model = BigBirdModel(config=config)\n model.to(torch_device)\n model.eval()\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)\n result = model(input_ids, token_type_ids=token_type_ids)\n result = model(input_ids)\n self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))\n\n def create_and_check_for_pretraining(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n model = BigBirdForPreTraining(config=config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids,\n attention_mask=input_mask,\n token_type_ids=token_type_ids,\n labels=token_labels,\n next_sentence_label=sequence_labels,\n )\n self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size))\n self.parent.assertEqual(result.seq_relationship_logits.shape, (self.batch_size, config.num_labels))\n\n def create_and_check_model_as_decoder(\n self,\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n encoder_hidden_states,\n encoder_attention_mask,\n ):\n config.add_cross_attention = True\n model = BigBirdModel(config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids,\n attention_mask=input_mask,\n token_type_ids=token_type_ids,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n )\n result = model(\n input_ids,\n attention_mask=input_mask,\n token_type_ids=token_type_ids,\n encoder_hidden_states=encoder_hidden_states,\n )\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)\n self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))\n\n def create_and_check_for_causal_lm(\n self,\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n encoder_hidden_states,\n encoder_attention_mask,\n ):\n model = BigBirdForCausalLM(config=config)\n model.to(torch_device)\n model.eval()\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))\n\n def create_and_check_for_masked_lm(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n model = BigBirdForMaskedLM(config=config)\n model.to(torch_device)\n model.eval()\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))\n\n def create_and_check_decoder_model_past_large_inputs(\n self,\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n encoder_hidden_states,\n encoder_attention_mask,\n ):\n config.is_decoder = True\n config.add_cross_attention = True\n model = BigBirdForCausalLM(config=config)\n model.to(torch_device)\n model.eval()\n\n # first forward pass\n outputs = model(\n input_ids,\n attention_mask=input_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=True,\n )\n past_key_values = outputs.past_key_values\n\n # create hypothetical multiple next token and extent to next_input_ids\n next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)\n next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)\n\n # append to next input_ids and\n next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)\n\n output_from_no_past = model(\n next_input_ids,\n attention_mask=next_attention_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n output_hidden_states=True,\n )[\"hidden_states\"][0]\n output_from_past = model(\n next_tokens,\n attention_mask=next_attention_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n past_key_values=past_key_values,\n output_hidden_states=True,\n )[\"hidden_states\"][0]\n\n # select random slice\n random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()\n output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()\n output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()\n\n self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])\n\n # test that outputs are equal for slice\n self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))\n\n def create_and_check_for_question_answering(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n model = BigBirdForQuestionAnswering(config=config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids,\n attention_mask=input_mask,\n token_type_ids=token_type_ids,\n start_positions=sequence_labels,\n end_positions=sequence_labels,\n )\n self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))\n self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))\n\n def create_and_check_for_sequence_classification(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n config.num_labels = self.num_labels\n model = BigBirdForSequenceClassification(config)\n model.to(torch_device)\n model.eval()\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))\n\n def create_and_check_for_token_classification(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n config.num_labels = self.num_labels\n model = BigBirdForTokenClassification(config=config)\n model.to(torch_device)\n model.eval()\n result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))\n\n def create_and_check_for_multiple_choice(\n self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\n ):\n config.num_choices = self.num_choices\n model = BigBirdForMultipleChoice(config=config)\n model.to(torch_device)\n model.eval()\n multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()\n multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()\n multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()\n result = model(\n multiple_choice_inputs_ids,\n attention_mask=multiple_choice_input_mask,\n token_type_ids=multiple_choice_token_type_ids,\n labels=choice_labels,\n )\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n ) = config_and_inputs\n inputs_dict = {\"input_ids\": input_ids, \"token_type_ids\": token_type_ids, \"attention_mask\": input_mask}\n return config, inputs_dict\n\n def create_and_check_for_auto_padding(\n self,\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n ):\n model = BigBirdModel(config)\n model.to(torch_device)\n model.eval()\n result = model(input_ids)\n self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))\n\n def create_and_check_for_change_to_full_attn(\n self,\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n ):\n model = BigBirdModel(config)\n model.to(torch_device)\n model.eval()\n result = model(input_ids)\n self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))\n # the config should not be changed\n self.parent.assertTrue(model.config.attention_type == \"block_sparse\")\n\n\n@require_torch\nclass BigBirdModelTest(ModelTesterMixin, unittest.TestCase):\n\n # head masking & pruning is currently not supported for big bird\n test_head_masking = False\n test_pruning = False\n\n # torchscript should be possible, but takes prohibitively long to test.\n # Also torchscript is not an important feature to have in the beginning.\n test_torchscript = False\n\n all_model_classes = (\n (\n BigBirdModel,\n BigBirdForPreTraining,\n BigBirdForMaskedLM,\n BigBirdForCausalLM,\n BigBirdForMultipleChoice,\n BigBirdForQuestionAnswering,\n BigBirdForSequenceClassification,\n BigBirdForTokenClassification,\n )\n if is_torch_available()\n else ()\n )\n all_generative_model_classes = (BigBirdForCausalLM,) if is_torch_available() else ()\n\n # special case for ForPreTraining model\n def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):\n inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)\n\n if return_labels:\n if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):\n inputs_dict[\"labels\"] = torch.zeros(\n (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device\n )\n inputs_dict[\"next_sentence_label\"] = torch.zeros(\n self.model_tester.batch_size, dtype=torch.long, device=torch_device\n )\n return inputs_dict\n\n def setUp(self):\n self.model_tester = BigBirdModelTester(self)\n self.config_tester = ConfigTester(self, config_class=BigBirdConfig, hidden_size=37)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_model(*config_and_inputs)\n\n def test_for_pretraining(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_pretraining(*config_and_inputs)\n\n def test_for_masked_lm(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)\n\n def test_for_multiple_choice(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)\n\n def test_decoder_model_past_with_large_inputs(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()\n self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)\n\n def test_for_question_answering(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_question_answering(*config_and_inputs)\n\n def test_for_sequence_classification(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)\n\n def test_for_token_classification(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_token_classification(*config_and_inputs)\n\n def test_model_as_decoder(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()\n self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)\n\n def test_model_as_decoder_with_default_input_mask(self):\n # This regression test was failing with PyTorch < 1.3\n (\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n encoder_hidden_states,\n encoder_attention_mask,\n ) = self.model_tester.prepare_config_and_inputs_for_decoder()\n\n input_mask = None\n\n self.model_tester.create_and_check_model_as_decoder(\n config,\n input_ids,\n token_type_ids,\n input_mask,\n sequence_labels,\n token_labels,\n choice_labels,\n encoder_hidden_states,\n encoder_attention_mask,\n )\n\n def test_retain_grad_hidden_states_attentions(self):\n # bigbird cannot keep gradients in attentions when `attention_type=block_sparse`\n\n if self.model_tester.attention_type == \"original_full\":\n super().test_retain_grad_hidden_states_attentions()\n\n @slow\n def test_model_from_pretrained(self):\n for model_name in BIG_BIRD_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\n model = BigBirdForPreTraining.from_pretrained(model_name)\n self.assertIsNotNone(model)\n\n def test_model_various_attn_type(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n for type in [\"original_full\", \"block_sparse\"]:\n config_and_inputs[0].attention_type = type\n self.model_tester.create_and_check_model(*config_and_inputs)\n\n def test_fast_integration(self):\n # fmt: off\n input_ids = torch.tensor(\n [[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 122, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 44, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 98, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73],[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 12, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 28, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 18, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73]], # noqa: E231\n dtype=torch.long,\n device=torch_device,\n )\n # fmt: on\n input_ids = input_ids % self.model_tester.vocab_size\n input_ids[1] = input_ids[1] - 1\n\n attention_mask = torch.ones((input_ids.shape), device=torch_device)\n attention_mask[:, :-10] = 0\n\n config, _, _, _, _, _, _ = self.model_tester.prepare_config_and_inputs()\n torch.manual_seed(0)\n model = BigBirdModel(config).eval().to(torch_device)\n\n with torch.no_grad():\n hidden_states = model(input_ids, attention_mask=attention_mask).last_hidden_state\n self.assertTrue(\n torch.allclose(\n hidden_states[0, 0, :5],\n torch.tensor([1.4825, 0.0774, 0.8226, -0.2962, -0.9593], device=torch_device),\n atol=1e-3,\n )\n )\n\n def test_auto_padding(self):\n self.model_tester.seq_length = 241\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_auto_padding(*config_and_inputs)\n\n def test_for_change_to_full_attn(self):\n self.model_tester.seq_length = 9\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_for_change_to_full_attn(*config_and_inputs)\n\n # overwrite from common in order to skip the check on `attentions`\n # also use `5e-5` to avoid flaky test failure\n def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=5e-5, name=\"outputs\", attributes=None):\n # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version,\n # an effort was done to return `attention_probs` (yet to be verified).\n if name.startswith(\"outputs.attentions\"):\n return\n else:\n super().check_pt_flax_outputs(fx_outputs, pt_outputs, model_class, tol, name, attributes)\n\n\n@require_torch\n@slow\nclass BigBirdModelIntegrationTest(unittest.TestCase):\n # we can have this true once block_sparse attn_probs works accurately\n test_attention_probs = False\n\n def _get_dummy_input_ids(self):\n # fmt: off\n ids = torch.tensor(\n [[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 122, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 44, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 98, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73]], # noqa: E231\n dtype=torch.long,\n device=torch_device,\n )\n # fmt: on\n return ids\n\n def test_inference_block_sparse_pretraining(self):\n model = BigBirdForPreTraining.from_pretrained(\"google/bigbird-roberta-base\", attention_type=\"block_sparse\")\n model.to(torch_device)\n\n input_ids = torch.tensor([[20920, 232, 328, 1437] * 1024], dtype=torch.long, device=torch_device)\n outputs = model(input_ids)\n prediction_logits = outputs.prediction_logits\n seq_relationship_logits = outputs.seq_relationship_logits\n\n self.assertEqual(prediction_logits.shape, torch.Size((1, 4096, 50358)))\n self.assertEqual(seq_relationship_logits.shape, torch.Size((1, 2)))\n\n expected_prediction_logits_slice = torch.tensor(\n [\n [-0.2420, -0.6048, -0.0614, 7.8422],\n [-0.0596, -0.0104, -1.8408, 9.3352],\n [1.0588, 0.7999, 5.0770, 8.7555],\n [-0.1385, -1.7199, -1.7613, 6.1094],\n ],\n device=torch_device,\n )\n self.assertTrue(\n torch.allclose(prediction_logits[0, 128:132, 128:132], expected_prediction_logits_slice, atol=1e-4)\n )\n\n expected_seq_relationship_logits = torch.tensor([[58.8196, 56.3629]], device=torch_device)\n self.assertTrue(torch.allclose(seq_relationship_logits, expected_seq_relationship_logits, atol=1e-4))\n\n def test_inference_full_pretraining(self):\n model = BigBirdForPreTraining.from_pretrained(\"google/bigbird-roberta-base\", attention_type=\"original_full\")\n model.to(torch_device)\n\n input_ids = torch.tensor([[20920, 232, 328, 1437] * 512], dtype=torch.long, device=torch_device)\n outputs = model(input_ids)\n prediction_logits = outputs.prediction_logits\n seq_relationship_logits = outputs.seq_relationship_logits\n\n self.assertEqual(prediction_logits.shape, torch.Size((1, 512 * 4, 50358)))\n self.assertEqual(seq_relationship_logits.shape, torch.Size((1, 2)))\n\n expected_prediction_logits_slice = torch.tensor(\n [\n [0.1499, -1.1217, 0.1990, 8.4499],\n [-2.7757, -3.0687, -4.8577, 7.5156],\n [1.5446, 0.1982, 4.3016, 10.4281],\n [-1.3705, -4.0130, -3.9629, 5.1526],\n ],\n device=torch_device,\n )\n self.assertTrue(\n torch.allclose(prediction_logits[0, 128:132, 128:132], expected_prediction_logits_slice, atol=1e-4)\n )\n\n expected_seq_relationship_logits = torch.tensor([[41.4503, 41.2406]], device=torch_device)\n self.assertTrue(torch.allclose(seq_relationship_logits, expected_seq_relationship_logits, atol=1e-4))\n\n def test_block_sparse_attention_probs(self):\n \"\"\"\n Asserting if outputted attention matrix is similar to hard coded attention matrix\n \"\"\"\n\n if not self.test_attention_probs:\n return\n\n model = BigBirdModel.from_pretrained(\n \"google/bigbird-roberta-base\", attention_type=\"block_sparse\", num_random_blocks=3, block_size=16\n )\n model.to(torch_device)\n model.eval()\n config = model.config\n\n input_ids = self._get_dummy_input_ids()\n\n hidden_states = model.embeddings(input_ids)\n\n batch_size, seqlen, _ = hidden_states.size()\n attn_mask = torch.ones(batch_size, seqlen, device=torch_device, dtype=torch.float)\n to_seq_length = from_seq_length = seqlen\n from_block_size = to_block_size = config.block_size\n\n blocked_mask, band_mask, from_mask, to_mask = model.create_masks_for_block_sparse_attn(\n attn_mask, config.block_size\n )\n from_blocked_mask = to_blocked_mask = blocked_mask\n\n for i in range(config.num_hidden_layers):\n pointer = model.encoder.layer[i].attention.self\n\n query_layer = pointer.transpose_for_scores(pointer.query(hidden_states))\n key_layer = pointer.transpose_for_scores(pointer.key(hidden_states))\n value_layer = pointer.transpose_for_scores(pointer.value(hidden_states))\n\n context_layer, attention_probs = pointer.bigbird_block_sparse_attention(\n query_layer,\n key_layer,\n value_layer,\n band_mask,\n from_mask,\n to_mask,\n from_blocked_mask,\n to_blocked_mask,\n pointer.num_attention_heads,\n pointer.num_random_blocks,\n pointer.attention_head_size,\n from_block_size,\n to_block_size,\n batch_size,\n from_seq_length,\n to_seq_length,\n seed=pointer.seed,\n plan_from_length=None,\n plan_num_rand_blocks=None,\n output_attentions=True,\n )\n\n context_layer = context_layer.contiguous().view(batch_size, from_seq_length, -1)\n cl = torch.einsum(\"bhqk,bhkd->bhqd\", attention_probs, value_layer)\n cl = cl.view(context_layer.size())\n\n self.assertTrue(torch.allclose(context_layer, cl, atol=0.001))\n\n def test_block_sparse_context_layer(self):\n model = BigBirdModel.from_pretrained(\n \"google/bigbird-roberta-base\", attention_type=\"block_sparse\", num_random_blocks=3, block_size=16\n )\n model.to(torch_device)\n model.eval()\n config = model.config\n\n input_ids = self._get_dummy_input_ids()\n dummy_hidden_states = model.embeddings(input_ids)\n\n attn_mask = torch.ones_like(input_ids, device=torch_device)\n blocked_mask, band_mask, from_mask, to_mask = model.create_masks_for_block_sparse_attn(\n attn_mask, config.block_size\n )\n targeted_cl = torch.tensor(\n [\n [0.1874, 1.5260, 0.2335, -0.0473, -0.0961, 1.8384, -0.0141, 0.1250, 0.0085, -0.0048],\n [-0.0554, 0.0728, 0.1683, -0.1332, 0.1741, 0.1337, -0.2380, -0.1849, -0.0390, -0.0259],\n [-0.0419, 0.0767, 0.1591, -0.1399, 0.1789, 0.1257, -0.2406, -0.1772, -0.0261, -0.0079],\n [0.1860, 1.5172, 0.2326, -0.0473, -0.0953, 1.8291, -0.0147, 0.1245, 0.0082, -0.0046],\n [0.1879, 1.5296, 0.2335, -0.0471, -0.0975, 1.8433, -0.0136, 0.1260, 0.0086, -0.0054],\n [0.1854, 1.5147, 0.2334, -0.0480, -0.0956, 1.8250, -0.0149, 0.1222, 0.0082, -0.0060],\n [0.1859, 1.5184, 0.2334, -0.0474, -0.0955, 1.8297, -0.0143, 0.1234, 0.0079, -0.0054],\n [0.1885, 1.5336, 0.2335, -0.0467, -0.0979, 1.8481, -0.0130, 0.1269, 0.0085, -0.0049],\n [0.1881, 1.5305, 0.2335, -0.0471, -0.0976, 1.8445, -0.0135, 0.1262, 0.0086, -0.0053],\n [0.1852, 1.5148, 0.2333, -0.0480, -0.0949, 1.8254, -0.0151, 0.1225, 0.0079, -0.0055],\n [0.1877, 1.5292, 0.2335, -0.0470, -0.0972, 1.8431, -0.0135, 0.1259, 0.0084, -0.0052],\n [0.1874, 1.5261, 0.2334, -0.0472, -0.0968, 1.8393, -0.0140, 0.1251, 0.0084, -0.0052],\n [0.1853, 1.5151, 0.2331, -0.0478, -0.0948, 1.8256, -0.0154, 0.1228, 0.0086, -0.0052],\n [0.1867, 1.5233, 0.2334, -0.0475, -0.0965, 1.8361, -0.0139, 0.1247, 0.0084, -0.0054],\n ],\n device=torch_device,\n )\n\n context_layer = model.encoder.layer[0].attention.self(\n dummy_hidden_states,\n band_mask=band_mask,\n from_mask=from_mask,\n to_mask=to_mask,\n from_blocked_mask=blocked_mask,\n to_blocked_mask=blocked_mask,\n )\n context_layer = context_layer[0]\n\n self.assertEqual(context_layer.shape, torch.Size((1, 128, 768)))\n self.assertTrue(torch.allclose(context_layer[0, 64:78, 300:310], targeted_cl, atol=0.0001))\n\n def test_tokenizer_inference(self):\n tokenizer = BigBirdTokenizer.from_pretrained(\"google/bigbird-roberta-base\")\n model = BigBirdModel.from_pretrained(\n \"google/bigbird-roberta-base\", attention_type=\"block_sparse\", num_random_blocks=3, block_size=16\n )\n model.to(torch_device)\n\n text = [\n \"Transformer-based models are unable to process long sequences due to their self-attention operation,\"\n \" which scales quadratically with the sequence length. To address this limitation, we introduce the\"\n \" Longformer with an attention mechanism that scales linearly with sequence length, making it easy to\"\n \" process documents of thousands of tokens or longer. Longformer’s attention mechanism is a drop-in\"\n \" replacement for the standard self-attention and combines a local windowed attention with a task\"\n \" motivated global attention. Following prior work on long-sequence transformers, we evaluate Longformer\"\n \" on character-level language modeling and achieve state-of-the-art results on text8 and enwik8. In\"\n \" contrast to most prior work, we also pretrain Longformer and finetune it on a variety of downstream\"\n \" tasks. Our pretrained Longformer consistently outperforms RoBERTa on long document tasks and sets new\"\n \" state-of-the-art results on WikiHop and TriviaQA.\"\n ]\n inputs = tokenizer(text)\n\n for k in inputs:\n inputs[k] = torch.tensor(inputs[k], device=torch_device, dtype=torch.long)\n\n prediction = model(**inputs)\n prediction = prediction[0]\n\n self.assertEqual(prediction.shape, torch.Size((1, 199, 768)))\n\n expected_prediction = torch.tensor(\n [\n [-0.0213, -0.2213, -0.0061, 0.0687],\n [0.0977, 0.1858, 0.2374, 0.0483],\n [0.2112, -0.2524, 0.5793, 0.0967],\n [0.2473, -0.5070, -0.0630, 0.2174],\n [0.2885, 0.1139, 0.6071, 0.2991],\n [0.2328, -0.2373, 0.3648, 0.1058],\n [0.2517, -0.0689, 0.0555, 0.0880],\n [0.1021, -0.1495, -0.0635, 0.1891],\n [0.0591, -0.0722, 0.2243, 0.2432],\n [-0.2059, -0.2679, 0.3225, 0.6183],\n [0.2280, -0.2618, 0.1693, 0.0103],\n [0.0183, -0.1375, 0.2284, -0.1707],\n ],\n device=torch_device,\n )\n self.assertTrue(torch.allclose(prediction[0, 52:64, 320:324], expected_prediction, atol=1e-4))\n\n def test_inference_question_answering(self):\n tokenizer = BigBirdTokenizer.from_pretrained(\"google/bigbird-base-trivia-itc\")\n model = BigBirdForQuestionAnswering.from_pretrained(\n \"google/bigbird-base-trivia-itc\", attention_type=\"block_sparse\", block_size=16, num_random_blocks=3\n )\n model.to(torch_device)\n\n context = (\n \"The BigBird model was proposed in Big Bird: Transformers for Longer Sequences by Zaheer, Manzil and\"\n \" Guruganesh, Guru and Dubey, Kumar Avinava and Ainslie, Joshua and Alberti, Chris and Ontanon, Santiago\"\n \" and Pham, Philip and Ravula, Anirudh and Wang, Qifan and Yang, Li and others. BigBird, is a\"\n \" sparse-attention based transformer which extends Transformer based models, such as BERT to much longer\"\n \" sequences. In addition to sparse attention, BigBird also applies global attention as well as random\"\n \" attention to the input sequence. Theoretically, it has been shown that applying sparse, global, and\"\n \" random attention approximates full attention, while being computationally much more efficient for longer\"\n \" sequences. As a consequence of the capability to handle longer context, BigBird has shown improved\"\n \" performance on various long document NLP tasks, such as question answering and summarization, compared\"\n \" to BERT or RoBERTa.\"\n )\n\n question = [\n \"Which is better for longer sequences- BigBird or BERT?\",\n \"What is the benefit of using BigBird over BERT?\",\n ]\n inputs = tokenizer(\n question,\n [context, context],\n padding=True,\n return_tensors=\"pt\",\n add_special_tokens=True,\n max_length=256,\n truncation=True,\n )\n\n inputs = {k: v.to(torch_device) for k, v in inputs.items()}\n\n start_logits, end_logits = model(**inputs).to_tuple()\n\n # fmt: off\n target_start_logits = torch.tensor(\n [[-8.9304, -10.3849, -14.4997, -9.6497, -13.9469, -7.8134, -8.9687, -13.3585, -9.7987, -13.8869, -9.2632, -8.9294, -13.6721, -7.3198, -9.5434, -11.2641, -14.3245, -9.5705, -12.7367, -8.6168, -11.083, -13.7573, -8.1151, -14.5329, -7.6876, -15.706, -12.8558, -9.1135, 8.0909, -3.1925, -11.5812, -9.4822], [-11.5595, -14.5591, -10.2978, -14.8445, -10.2092, -11.1899, -13.8356, -10.5644, -14.7706, -9.9841, -11.0052, -14.1862, -8.8173, -11.1098, -12.4686, -15.0531, -11.0196, -13.6614, -10.0236, -11.8151, -14.8744, -9.5123, -15.1605, -8.6472, -15.4184, -8.898, -9.6328, -7.0258, -11.3365, -14.4065, -10.2587, -8.9103]], # noqa: E231\n device=torch_device,\n )\n target_end_logits = torch.tensor(\n [[-12.4131, -8.5959, -15.7163, -11.1524, -15.9913, -12.2038, -7.8902, -16.0296, -12.164, -16.5017, -13.3332, -6.9488, -15.7756, -13.8506, -11.0779, -9.2893, -15.0426, -10.1963, -17.3292, -12.2945, -11.5337, -16.4514, -9.1564, -17.5001, -9.1562, -16.2971, -13.3199, -7.5724, -5.1175, 7.2168, -10.3804, -11.9873], [-10.8654, -14.9967, -11.4144, -16.9189, -14.2673, -9.7068, -15.0182, -12.8846, -16.8716, -13.665, -10.3113, -15.1436, -14.9069, -13.3364, -11.2339, -16.0118, -11.8331, -17.0613, -13.8852, -12.4163, -16.8978, -10.7772, -17.2324, -10.6979, -16.9811, -10.3427, -9.497, -13.7104, -11.1107, -13.2936, -13.855, -14.1264]], # noqa: E231\n device=torch_device,\n )\n # fmt: on\n\n self.assertTrue(torch.allclose(start_logits[:, 64:96], target_start_logits, atol=1e-4))\n self.assertTrue(torch.allclose(end_logits[:, 64:96], target_end_logits, atol=1e-4))\n\n input_ids = inputs[\"input_ids\"].tolist()\n answer = [\n input_ids[i][torch.argmax(start_logits, dim=-1)[i] : torch.argmax(end_logits, dim=-1)[i] + 1]\n for i in range(len(input_ids))\n ]\n answer = tokenizer.batch_decode(answer)\n\n self.assertTrue(answer == [\"BigBird\", \"global attention\"])\n\n def test_fill_mask(self):\n tokenizer = BigBirdTokenizer.from_pretrained(\"google/bigbird-roberta-base\")\n model = BigBirdForMaskedLM.from_pretrained(\"google/bigbird-roberta-base\")\n model.to(torch_device)\n\n input_ids = tokenizer(\"The goal of life is [MASK] .\", return_tensors=\"pt\").input_ids.to(torch_device)\n logits = model(input_ids).logits\n\n # [MASK] is token at 6th position\n pred_token = tokenizer.decode(torch.argmax(logits[0, 6:7], axis=-1))\n self.assertEqual(pred_token, \"happiness\")\n\n def test_auto_padding(self):\n model = BigBirdModel.from_pretrained(\n \"google/bigbird-roberta-base\", attention_type=\"block_sparse\", num_random_blocks=3, block_size=16\n )\n model.to(torch_device)\n model.eval()\n\n input_ids = torch.tensor([200 * [10] + 40 * [2] + [1]], device=torch_device, dtype=torch.long)\n output = model(input_ids).to_tuple()[0]\n\n # fmt: off\n target = torch.tensor(\n [[-0.045136, -0.068013, 0.12246, -0.01356, 0.018386, 0.025333, -0.0044439, -0.0030996, -0.064031, 0.0006439], [-0.045018, -0.067638, 0.12317, -0.013998, 0.019216, 0.025695, -0.0043705, -0.0031895, -0.063153, 0.00088899], [-0.045042, -0.067305, 0.1234, -0.014512, 0.020057, 0.026084, -0.004615, -0.0031728, -0.062442, 0.0010263], [-0.044589, -0.067655, 0.12416, -0.014287, 0.019416, 0.026065, -0.0050958, -0.002702, -0.063158, 0.0004827], [-0.044627, -0.067535, 0.1239, -0.014319, 0.019491, 0.026213, -0.0059482, -0.0025906, -0.063116, 0.00014669], [-0.044899, -0.067704, 0.12337, -0.014231, 0.019256, 0.026345, -0.0065565, -0.0022938, -0.063433, -0.00011409], [-0.045599, -0.067764, 0.12235, -0.014151, 0.019206, 0.026417, -0.0068965, -0.0024494, -0.063313, -4.4499e-06], [-0.045557, -0.068372, 0.12199, -0.013747, 0.017962, 0.026103, -0.0070607, -0.0023552, -0.06447, -0.00048756], [-0.045334, -0.068913, 0.1217, -0.013566, 0.01693, 0.025745, -0.006311, -0.0024903, -0.065575, -0.0006719], [-0.045171, -0.068726, 0.12164, -0.013688, 0.017139, 0.025629, -0.005213, -0.0029412, -0.065237, -0.00020669], [-0.044411, -0.069267, 0.12206, -0.013645, 0.016212, 0.025589, -0.0044121, -0.002972, -0.066277, -0.00067963], [-0.043487, -0.069792, 0.1232, -0.013663, 0.015303, 0.02613, -0.0036294, -0.0030616, -0.067483, -0.0012642], [-0.042622, -0.069287, 0.12469, -0.013936, 0.016204, 0.026474, -0.0040534, -0.0027365, -0.066994, -0.0014148], [-0.041879, -0.070031, 0.12593, -0.014047, 0.015082, 0.027751, -0.0040683, -0.0027189, -0.068985, -0.0027146]], # noqa: E231\n device=torch_device,\n )\n # fmt: on\n\n self.assertEqual(output.shape, torch.Size((1, 241, 768)))\n self.assertTrue(torch.allclose(output[0, 64:78, 300:310], target, atol=0.0001))\n", "# coding=utf-8\n# Copyright 2020 The Allen Institute for AI team and The HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"PyTorch Longformer model.\"\"\"\n\nimport math\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple, Union\n\nimport torch\nimport torch.utils.checkpoint\nfrom torch import nn\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\n\nfrom ...activations import ACT2FN, gelu\nfrom ...modeling_utils import PreTrainedModel\nfrom ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer\nfrom ...utils import (\n ModelOutput,\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n logging,\n replace_return_docstrings,\n)\nfrom .configuration_longformer import LongformerConfig\n\n\nlogger = logging.get_logger(__name__)\n\n_CHECKPOINT_FOR_DOC = \"allenai/longformer-base-4096\"\n_CONFIG_FOR_DOC = \"LongformerConfig\"\n_TOKENIZER_FOR_DOC = \"LongformerTokenizer\"\n\nLONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"allenai/longformer-base-4096\",\n \"allenai/longformer-large-4096\",\n \"allenai/longformer-large-4096-finetuned-triviaqa\",\n \"allenai/longformer-base-4096-extra.pos.embd.only\",\n \"allenai/longformer-large-4096-extra.pos.embd.only\",\n # See all Longformer models at https://huggingface.co/models?filter=longformer\n]\n\n\n@dataclass\nclass LongformerBaseModelOutput(ModelOutput):\n \"\"\"\n Base class for Longformer's outputs, with potential hidden states, local and global attentions.\n\n Args:\n last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the model.\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +\n attention_window + 1)`, where `x` is the number of tokens with global attention mask.\n\n Local attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token in the sequence to every token with\n global attention (first `x` values) and to every token in the attention window (remaining `attention_window\n + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the\n remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a\n token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding\n (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.\n If the attention window contains a token with global attention, the attention weight at the corresponding\n index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global\n attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be\n accessed from `global_attentions`.\n global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,\n where `x` is the number of tokens with global attention mask.\n\n Global attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token with global attention to every token\n in the sequence.\n \"\"\"\n\n last_hidden_state: torch.FloatTensor\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n global_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass LongformerBaseModelOutputWithPooling(ModelOutput):\n \"\"\"\n Base class for Longformer's outputs that also contains a pooling of the last hidden states.\n\n Args:\n last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the model.\n pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):\n Last layer hidden-state of the first token of the sequence (classification token) further processed by a\n Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence\n prediction (classification) objective during pretraining.\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +\n attention_window + 1)`, where `x` is the number of tokens with global attention mask.\n\n Local attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token in the sequence to every token with\n global attention (first `x` values) and to every token in the attention window (remaining `attention_window\n + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the\n remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a\n token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding\n (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.\n If the attention window contains a token with global attention, the attention weight at the corresponding\n index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global\n attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be\n accessed from `global_attentions`.\n global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,\n where `x` is the number of tokens with global attention mask.\n\n Global attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token with global attention to every token\n in the sequence.\n \"\"\"\n\n last_hidden_state: torch.FloatTensor\n pooler_output: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n global_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass LongformerMaskedLMOutput(ModelOutput):\n \"\"\"\n Base class for masked language models outputs.\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):\n Masked language modeling (MLM) loss.\n logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +\n attention_window + 1)`, where `x` is the number of tokens with global attention mask.\n\n Local attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token in the sequence to every token with\n global attention (first `x` values) and to every token in the attention window (remaining `attention_window\n + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the\n remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a\n token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding\n (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.\n If the attention window contains a token with global attention, the attention weight at the corresponding\n index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global\n attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be\n accessed from `global_attentions`.\n global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,\n where `x` is the number of tokens with global attention mask.\n\n Global attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token with global attention to every token\n in the sequence.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n logits: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n global_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass LongformerQuestionAnsweringModelOutput(ModelOutput):\n \"\"\"\n Base class for outputs of question answering Longformer models.\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):\n Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.\n start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):\n Span-start scores (before SoftMax).\n end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):\n Span-end scores (before SoftMax).\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +\n attention_window + 1)`, where `x` is the number of tokens with global attention mask.\n\n Local attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token in the sequence to every token with\n global attention (first `x` values) and to every token in the attention window (remaining `attention_window\n + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the\n remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a\n token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding\n (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.\n If the attention window contains a token with global attention, the attention weight at the corresponding\n index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global\n attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be\n accessed from `global_attentions`.\n global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,\n where `x` is the number of tokens with global attention mask.\n\n Global attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token with global attention to every token\n in the sequence.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n start_logits: torch.FloatTensor = None\n end_logits: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n global_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass LongformerSequenceClassifierOutput(ModelOutput):\n \"\"\"\n Base class for outputs of sentence classification models.\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):\n Classification (or regression if config.num_labels==1) loss.\n logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):\n Classification (or regression if config.num_labels==1) scores (before SoftMax).\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +\n attention_window + 1)`, where `x` is the number of tokens with global attention mask.\n\n Local attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token in the sequence to every token with\n global attention (first `x` values) and to every token in the attention window (remaining `attention_window\n + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the\n remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a\n token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding\n (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.\n If the attention window contains a token with global attention, the attention weight at the corresponding\n index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global\n attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be\n accessed from `global_attentions`.\n global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,\n where `x` is the number of tokens with global attention mask.\n\n Global attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token with global attention to every token\n in the sequence.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n logits: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n global_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass LongformerMultipleChoiceModelOutput(ModelOutput):\n \"\"\"\n Base class for outputs of multiple choice Longformer models.\n\n Args:\n loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):\n Classification loss.\n logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):\n *num_choices* is the second dimension of the input tensors. (see *input_ids* above).\n\n Classification scores (before SoftMax).\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +\n attention_window + 1)`, where `x` is the number of tokens with global attention mask.\n\n Local attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token in the sequence to every token with\n global attention (first `x` values) and to every token in the attention window (remaining `attention_window\n + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the\n remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a\n token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding\n (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.\n If the attention window contains a token with global attention, the attention weight at the corresponding\n index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global\n attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be\n accessed from `global_attentions`.\n global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,\n where `x` is the number of tokens with global attention mask.\n\n Global attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token with global attention to every token\n in the sequence.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n logits: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n global_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass LongformerTokenClassifierOutput(ModelOutput):\n \"\"\"\n Base class for outputs of token classification models.\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) :\n Classification loss.\n logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):\n Classification scores (before SoftMax).\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +\n attention_window + 1)`, where `x` is the number of tokens with global attention mask.\n\n Local attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token in the sequence to every token with\n global attention (first `x` values) and to every token in the attention window (remaining `attention_window\n + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the\n remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a\n token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding\n (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.\n If the attention window contains a token with global attention, the attention weight at the corresponding\n index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global\n attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be\n accessed from `global_attentions`.\n global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,\n where `x` is the number of tokens with global attention mask.\n\n Global attentions weights after the attention softmax, used to compute the weighted average in the\n self-attention heads. Those are the attention weights from every token with global attention to every token\n in the sequence.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n logits: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n global_attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\ndef _get_question_end_index(input_ids, sep_token_id):\n \"\"\"\n Computes the index of the first occurrence of `sep_token_id`.\n \"\"\"\n\n sep_token_indices = (input_ids == sep_token_id).nonzero()\n batch_size = input_ids.shape[0]\n\n assert sep_token_indices.shape[1] == 2, \"`input_ids` should have two dimensions\"\n assert sep_token_indices.shape[0] == 3 * batch_size, (\n f\"There should be exactly three separator tokens: {sep_token_id} in every sample for questions answering. You\"\n \" might also consider to set `global_attention_mask` manually in the forward function to avoid this error.\"\n )\n return sep_token_indices.view(batch_size, 3, 2)[:, 0, 1]\n\n\ndef _compute_global_attention_mask(input_ids, sep_token_id, before_sep_token=True):\n \"\"\"\n Computes global attention mask by putting attention on all tokens before `sep_token_id` if `before_sep_token is\n True` else after `sep_token_id`.\n \"\"\"\n question_end_index = _get_question_end_index(input_ids, sep_token_id)\n question_end_index = question_end_index.unsqueeze(dim=1) # size: batch_size x 1\n # bool attention mask with True in locations of global attention\n attention_mask = torch.arange(input_ids.shape[1], device=input_ids.device)\n if before_sep_token is True:\n attention_mask = (attention_mask.expand_as(input_ids) < question_end_index).to(torch.uint8)\n else:\n # last token is separation token and should not be counted and in the middle are two separation tokens\n attention_mask = (attention_mask.expand_as(input_ids) > (question_end_index + 1)).to(torch.uint8) * (\n attention_mask.expand_as(input_ids) < input_ids.shape[-1]\n ).to(torch.uint8)\n\n return attention_mask\n\n\ndef create_position_ids_from_input_ids(input_ids, padding_idx):\n \"\"\"\n Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols\n are ignored. This is modified from fairseq's `utils.make_positions`.\n\n Args:\n x: torch.Tensor x:\n\n Returns: torch.Tensor\n \"\"\"\n # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.\n mask = input_ids.ne(padding_idx).int()\n incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask\n return incremental_indices.long() + padding_idx\n\n\nclass LongformerEmbeddings(nn.Module):\n \"\"\"\n Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n # position_ids (1, len position emb) is contiguous in memory and exported when serialized\n self.register_buffer(\"position_ids\", torch.arange(config.max_position_embeddings).expand((1, -1)))\n self.position_embedding_type = getattr(config, \"position_embedding_type\", \"absolute\")\n\n self.padding_idx = config.pad_token_id\n self.position_embeddings = nn.Embedding(\n config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx\n )\n\n def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):\n if position_ids is None:\n if input_ids is not None:\n # Create the position ids from the input token ids. Any padded tokens remain padded.\n position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx).to(input_ids.device)\n else:\n position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)\n\n if input_ids is not None:\n input_shape = input_ids.size()\n else:\n input_shape = inputs_embeds.size()[:-1]\n\n seq_length = input_shape[1]\n\n if position_ids is None:\n position_ids = self.position_ids[:, :seq_length]\n\n if token_type_ids is None:\n token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)\n\n if inputs_embeds is None:\n inputs_embeds = self.word_embeddings(input_ids)\n position_embeddings = self.position_embeddings(position_ids)\n token_type_embeddings = self.token_type_embeddings(token_type_ids)\n\n embeddings = inputs_embeds + position_embeddings + token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n def create_position_ids_from_inputs_embeds(self, inputs_embeds):\n \"\"\"\n We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.\n\n Args:\n inputs_embeds: torch.Tensor inputs_embeds:\n\n Returns: torch.Tensor\n \"\"\"\n input_shape = inputs_embeds.size()[:-1]\n sequence_length = input_shape[1]\n\n position_ids = torch.arange(\n self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device\n )\n return position_ids.unsqueeze(0).expand(input_shape)\n\n\nclass LongformerSelfAttention(nn.Module):\n def __init__(self, config, layer_id):\n super().__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n f\"The hidden size ({config.hidden_size}) is not a multiple of the number of attention \"\n f\"heads ({config.num_attention_heads})\"\n )\n self.num_heads = config.num_attention_heads\n self.head_dim = int(config.hidden_size / config.num_attention_heads)\n self.embed_dim = config.hidden_size\n\n self.query = nn.Linear(config.hidden_size, self.embed_dim)\n self.key = nn.Linear(config.hidden_size, self.embed_dim)\n self.value = nn.Linear(config.hidden_size, self.embed_dim)\n\n # separate projection layers for tokens with global attention\n self.query_global = nn.Linear(config.hidden_size, self.embed_dim)\n self.key_global = nn.Linear(config.hidden_size, self.embed_dim)\n self.value_global = nn.Linear(config.hidden_size, self.embed_dim)\n\n self.dropout = config.attention_probs_dropout_prob\n\n self.layer_id = layer_id\n attention_window = config.attention_window[self.layer_id]\n assert (\n attention_window % 2 == 0\n ), f\"`attention_window` for layer {self.layer_id} has to be an even value. Given {attention_window}\"\n assert (\n attention_window > 0\n ), f\"`attention_window` for layer {self.layer_id} has to be positive. Given {attention_window}\"\n\n self.one_sided_attn_window_size = attention_window // 2\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n layer_head_mask=None,\n is_index_masked=None,\n is_index_global_attn=None,\n is_global_attn=None,\n output_attentions=False,\n ):\n \"\"\"\n [`LongformerSelfAttention`] expects *len(hidden_states)* to be multiple of *attention_window*. Padding to\n *attention_window* happens in [`LongformerModel.forward`] to avoid redoing the padding on each layer.\n\n The *attention_mask* is changed in [`LongformerModel.forward`] from 0, 1, 2 to:\n\n - -10000: no attention\n - 0: local attention\n - +10000: global attention\n \"\"\"\n hidden_states = hidden_states.transpose(0, 1)\n\n # project hidden states\n query_vectors = self.query(hidden_states)\n key_vectors = self.key(hidden_states)\n value_vectors = self.value(hidden_states)\n\n seq_len, batch_size, embed_dim = hidden_states.size()\n assert (\n embed_dim == self.embed_dim\n ), f\"hidden_states should have embed_dim = {self.embed_dim}, but has {embed_dim}\"\n\n # normalize query\n query_vectors /= math.sqrt(self.head_dim)\n\n query_vectors = query_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)\n key_vectors = key_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)\n\n attn_scores = self._sliding_chunks_query_key_matmul(\n query_vectors, key_vectors, self.one_sided_attn_window_size\n )\n\n # values to pad for attention probs\n remove_from_windowed_attention_mask = (attention_mask != 0)[:, :, None, None]\n\n # cast to fp32/fp16 then replace 1's with -inf\n float_mask = remove_from_windowed_attention_mask.type_as(query_vectors).masked_fill(\n remove_from_windowed_attention_mask, torch.finfo(query_vectors.dtype).min\n )\n # diagonal mask with zeros everywhere and -inf inplace of padding\n diagonal_mask = self._sliding_chunks_query_key_matmul(\n float_mask.new_ones(size=float_mask.size()), float_mask, self.one_sided_attn_window_size\n )\n\n # pad local attention probs\n attn_scores += diagonal_mask\n\n assert list(attn_scores.size()) == [\n batch_size,\n seq_len,\n self.num_heads,\n self.one_sided_attn_window_size * 2 + 1,\n ], (\n f\"local_attn_probs should be of size ({batch_size}, {seq_len}, {self.num_heads},\"\n f\" {self.one_sided_attn_window_size * 2 + 1}), but is of size {attn_scores.size()}\"\n )\n\n # compute local attention probs from global attention keys and contact over window dim\n if is_global_attn:\n # compute global attn indices required through out forward fn\n (\n max_num_global_attn_indices,\n is_index_global_attn_nonzero,\n is_local_index_global_attn_nonzero,\n is_local_index_no_global_attn_nonzero,\n ) = self._get_global_attn_indices(is_index_global_attn)\n # calculate global attn probs from global key\n\n global_key_attn_scores = self._concat_with_global_key_attn_probs(\n query_vectors=query_vectors,\n key_vectors=key_vectors,\n max_num_global_attn_indices=max_num_global_attn_indices,\n is_index_global_attn_nonzero=is_index_global_attn_nonzero,\n is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,\n is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,\n )\n # concat to local_attn_probs\n # (batch_size, seq_len, num_heads, extra attention count + 2*window+1)\n attn_scores = torch.cat((global_key_attn_scores, attn_scores), dim=-1)\n\n # free memory\n del global_key_attn_scores\n\n attn_probs = nn.functional.softmax(\n attn_scores, dim=-1, dtype=torch.float32\n ) # use fp32 for numerical stability\n\n if layer_head_mask is not None:\n assert layer_head_mask.size() == (\n self.num_heads,\n ), f\"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}\"\n attn_probs = layer_head_mask.view(1, 1, -1, 1) * attn_probs\n\n # softmax sometimes inserts NaN if all positions are masked, replace them with 0\n attn_probs = torch.masked_fill(attn_probs, is_index_masked[:, :, None, None], 0.0)\n attn_probs = attn_probs.type_as(attn_scores)\n\n # free memory\n del attn_scores\n\n # apply dropout\n attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)\n\n value_vectors = value_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)\n\n # compute local attention output with global attention value and add\n if is_global_attn:\n # compute sum of global and local attn\n attn_output = self._compute_attn_output_with_global_indices(\n value_vectors=value_vectors,\n attn_probs=attn_probs,\n max_num_global_attn_indices=max_num_global_attn_indices,\n is_index_global_attn_nonzero=is_index_global_attn_nonzero,\n is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,\n )\n else:\n # compute local attn only\n attn_output = self._sliding_chunks_matmul_attn_probs_value(\n attn_probs, value_vectors, self.one_sided_attn_window_size\n )\n\n assert attn_output.size() == (batch_size, seq_len, self.num_heads, self.head_dim), \"Unexpected size\"\n attn_output = attn_output.transpose(0, 1).reshape(seq_len, batch_size, embed_dim).contiguous()\n\n # compute value for global attention and overwrite to attention output\n # TODO: remove the redundant computation\n if is_global_attn:\n global_attn_output, global_attn_probs = self._compute_global_attn_output_from_hidden(\n hidden_states=hidden_states,\n max_num_global_attn_indices=max_num_global_attn_indices,\n layer_head_mask=layer_head_mask,\n is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,\n is_index_global_attn_nonzero=is_index_global_attn_nonzero,\n is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,\n is_index_masked=is_index_masked,\n )\n\n # get only non zero global attn output\n nonzero_global_attn_output = global_attn_output[\n is_local_index_global_attn_nonzero[0], :, is_local_index_global_attn_nonzero[1]\n ]\n\n # overwrite values with global attention\n attn_output[is_index_global_attn_nonzero[::-1]] = nonzero_global_attn_output.view(\n len(is_local_index_global_attn_nonzero[0]), -1\n )\n # The attention weights for tokens with global attention are\n # just filler values, they were never used to compute the output.\n # Fill with 0 now, the correct values are in 'global_attn_probs'.\n attn_probs[is_index_global_attn_nonzero] = 0\n\n outputs = (attn_output.transpose(0, 1),)\n\n if output_attentions:\n outputs += (attn_probs,)\n\n return outputs + (global_attn_probs,) if (is_global_attn and output_attentions) else outputs\n\n @staticmethod\n def _pad_and_transpose_last_two_dims(hidden_states_padded, padding):\n \"\"\"pads rows and then flips rows and columns\"\"\"\n hidden_states_padded = nn.functional.pad(\n hidden_states_padded, padding\n ) # padding value is not important because it will be overwritten\n hidden_states_padded = hidden_states_padded.view(\n *hidden_states_padded.size()[:-2], hidden_states_padded.size(-1), hidden_states_padded.size(-2)\n )\n return hidden_states_padded\n\n @staticmethod\n def _pad_and_diagonalize(chunked_hidden_states):\n \"\"\"\n shift every row 1 step right, converting columns into diagonals.\n\n Example:\n\n ```python\n chunked_hidden_states: [\n 0.4983,\n 2.6918,\n -0.0071,\n 1.0492,\n -1.8348,\n 0.7672,\n 0.2986,\n 0.0285,\n -0.7584,\n 0.4206,\n -0.0405,\n 0.1599,\n 2.0514,\n -1.1600,\n 0.5372,\n 0.2629,\n ]\n window_overlap = num_rows = 4\n ```\n\n (pad & diagonalize) => [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000\n 0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 0.0000, 0.0000, -0.7584, 0.4206,\n -0.0405, 0.1599, 0.0000 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ]\n \"\"\"\n total_num_heads, num_chunks, window_overlap, hidden_dim = chunked_hidden_states.size()\n chunked_hidden_states = nn.functional.pad(\n chunked_hidden_states, (0, window_overlap + 1)\n ) # total_num_heads x num_chunks x window_overlap x (hidden_dim+window_overlap+1). Padding value is not important because it'll be overwritten\n chunked_hidden_states = chunked_hidden_states.view(\n total_num_heads, num_chunks, -1\n ) # total_num_heads x num_chunks x window_overlap*window_overlap+window_overlap\n chunked_hidden_states = chunked_hidden_states[\n :, :, :-window_overlap\n ] # total_num_heads x num_chunks x window_overlap*window_overlap\n chunked_hidden_states = chunked_hidden_states.view(\n total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim\n )\n chunked_hidden_states = chunked_hidden_states[:, :, :, :-1]\n return chunked_hidden_states\n\n @staticmethod\n def _chunk(hidden_states, window_overlap):\n \"\"\"convert into overlapping chunks. Chunk size = 2w, overlap size = w\"\"\"\n\n # non-overlapping chunks of size = 2w\n hidden_states = hidden_states.view(\n hidden_states.size(0),\n hidden_states.size(1) // (window_overlap * 2),\n window_overlap * 2,\n hidden_states.size(2),\n )\n\n # use `as_strided` to make the chunks overlap with an overlap size = window_overlap\n chunk_size = list(hidden_states.size())\n chunk_size[1] = chunk_size[1] * 2 - 1\n\n chunk_stride = list(hidden_states.stride())\n chunk_stride[1] = chunk_stride[1] // 2\n return hidden_states.as_strided(size=chunk_size, stride=chunk_stride)\n\n @staticmethod\n def _mask_invalid_locations(input_tensor, affected_seq_len) -> torch.Tensor:\n beginning_mask_2d = input_tensor.new_ones(affected_seq_len, affected_seq_len + 1).tril().flip(dims=[0])\n beginning_mask = beginning_mask_2d[None, :, None, :]\n ending_mask = beginning_mask.flip(dims=(1, 3))\n beginning_input = input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1]\n beginning_mask = beginning_mask.expand(beginning_input.size())\n beginning_input.masked_fill_(beginning_mask == 1, -float(\"inf\")) # `== 1` converts to bool or uint8\n ending_input = input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :]\n ending_mask = ending_mask.expand(ending_input.size())\n ending_input.masked_fill_(ending_mask == 1, -float(\"inf\")) # `== 1` converts to bool or uint8\n\n def _sliding_chunks_query_key_matmul(self, query: torch.Tensor, key: torch.Tensor, window_overlap: int):\n \"\"\"\n Matrix multiplication of query and key tensors using with a sliding window attention pattern. This\n implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained Longformer) with an\n overlap of size window_overlap\n \"\"\"\n batch_size, seq_len, num_heads, head_dim = query.size()\n assert (\n seq_len % (window_overlap * 2) == 0\n ), f\"Sequence length should be multiple of {window_overlap * 2}. Given {seq_len}\"\n assert query.size() == key.size()\n\n chunks_count = seq_len // window_overlap - 1\n\n # group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size window_overlap * 2\n query = query.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)\n key = key.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)\n\n query = self._chunk(query, window_overlap)\n key = self._chunk(key, window_overlap)\n\n # matrix multiplication\n # bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim\n # bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim\n # bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap\n diagonal_chunked_attention_scores = torch.einsum(\"bcxd,bcyd->bcxy\", (query, key)) # multiply\n\n # convert diagonals into columns\n diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims(\n diagonal_chunked_attention_scores, padding=(0, 0, 0, 1)\n )\n\n # allocate space for the overall attention matrix where the chunks are combined. The last dimension\n # has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to\n # window_overlap previous words). The following column is attention score from each word to itself, then\n # followed by window_overlap columns for the upper triangle.\n\n diagonal_attention_scores = diagonal_chunked_attention_scores.new_empty(\n (batch_size * num_heads, chunks_count + 1, window_overlap, window_overlap * 2 + 1)\n )\n\n # copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions\n # - copying the main diagonal and the upper triangle\n diagonal_attention_scores[:, :-1, :, window_overlap:] = diagonal_chunked_attention_scores[\n :, :, :window_overlap, : window_overlap + 1\n ]\n diagonal_attention_scores[:, -1, :, window_overlap:] = diagonal_chunked_attention_scores[\n :, -1, window_overlap:, : window_overlap + 1\n ]\n # - copying the lower triangle\n diagonal_attention_scores[:, 1:, :, :window_overlap] = diagonal_chunked_attention_scores[\n :, :, -(window_overlap + 1) : -1, window_overlap + 1 :\n ]\n\n diagonal_attention_scores[:, 0, 1:window_overlap, 1:window_overlap] = diagonal_chunked_attention_scores[\n :, 0, : window_overlap - 1, 1 - window_overlap :\n ]\n\n # separate batch_size and num_heads dimensions again\n diagonal_attention_scores = diagonal_attention_scores.view(\n batch_size, num_heads, seq_len, 2 * window_overlap + 1\n ).transpose(2, 1)\n\n self._mask_invalid_locations(diagonal_attention_scores, window_overlap)\n return diagonal_attention_scores\n\n def _sliding_chunks_matmul_attn_probs_value(\n self, attn_probs: torch.Tensor, value: torch.Tensor, window_overlap: int\n ):\n \"\"\"\n Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the\n same shape as `attn_probs`\n \"\"\"\n batch_size, seq_len, num_heads, head_dim = value.size()\n\n assert seq_len % (window_overlap * 2) == 0\n assert attn_probs.size()[:3] == value.size()[:3]\n assert attn_probs.size(3) == 2 * window_overlap + 1\n chunks_count = seq_len // window_overlap - 1\n # group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap\n\n chunked_attn_probs = attn_probs.transpose(1, 2).reshape(\n batch_size * num_heads, seq_len // window_overlap, window_overlap, 2 * window_overlap + 1\n )\n\n # group batch_size and num_heads dimensions into one\n value = value.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)\n\n # pad seq_len with w at the beginning of the sequence and another window overlap at the end\n padded_value = nn.functional.pad(value, (0, 0, window_overlap, window_overlap), value=-1)\n\n # chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap\n chunked_value_size = (batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim)\n chunked_value_stride = padded_value.stride()\n chunked_value_stride = (\n chunked_value_stride[0],\n window_overlap * chunked_value_stride[1],\n chunked_value_stride[1],\n chunked_value_stride[2],\n )\n chunked_value = padded_value.as_strided(size=chunked_value_size, stride=chunked_value_stride)\n\n chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs)\n\n context = torch.einsum(\"bcwd,bcdh->bcwh\", (chunked_attn_probs, chunked_value))\n return context.view(batch_size, num_heads, seq_len, head_dim).transpose(1, 2)\n\n @staticmethod\n def _get_global_attn_indices(is_index_global_attn):\n \"\"\"compute global attn indices required throughout forward pass\"\"\"\n # helper variable\n num_global_attn_indices = is_index_global_attn.long().sum(dim=1)\n\n # max number of global attn indices in batch\n max_num_global_attn_indices = num_global_attn_indices.max()\n\n # indices of global attn\n is_index_global_attn_nonzero = is_index_global_attn.nonzero(as_tuple=True)\n\n # helper variable\n is_local_index_global_attn = torch.arange(\n max_num_global_attn_indices, device=is_index_global_attn.device\n ) < num_global_attn_indices.unsqueeze(dim=-1)\n\n # location of the non-padding values within global attention indices\n is_local_index_global_attn_nonzero = is_local_index_global_attn.nonzero(as_tuple=True)\n\n # location of the padding values within global attention indices\n is_local_index_no_global_attn_nonzero = (is_local_index_global_attn == 0).nonzero(as_tuple=True)\n return (\n max_num_global_attn_indices,\n is_index_global_attn_nonzero,\n is_local_index_global_attn_nonzero,\n is_local_index_no_global_attn_nonzero,\n )\n\n def _concat_with_global_key_attn_probs(\n self,\n key_vectors,\n query_vectors,\n max_num_global_attn_indices,\n is_index_global_attn_nonzero,\n is_local_index_global_attn_nonzero,\n is_local_index_no_global_attn_nonzero,\n ):\n batch_size = key_vectors.shape[0]\n\n # create only global key vectors\n key_vectors_only_global = key_vectors.new_zeros(\n batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim\n )\n\n key_vectors_only_global[is_local_index_global_attn_nonzero] = key_vectors[is_index_global_attn_nonzero]\n\n # (batch_size, seq_len, num_heads, max_num_global_attn_indices)\n attn_probs_from_global_key = torch.einsum(\"blhd,bshd->blhs\", (query_vectors, key_vectors_only_global))\n\n attn_probs_from_global_key[\n is_local_index_no_global_attn_nonzero[0], :, :, is_local_index_no_global_attn_nonzero[1]\n ] = torch.finfo(attn_probs_from_global_key.dtype).min\n\n return attn_probs_from_global_key\n\n def _compute_attn_output_with_global_indices(\n self,\n value_vectors,\n attn_probs,\n max_num_global_attn_indices,\n is_index_global_attn_nonzero,\n is_local_index_global_attn_nonzero,\n ):\n batch_size = attn_probs.shape[0]\n\n # cut local attn probs to global only\n attn_probs_only_global = attn_probs.narrow(-1, 0, max_num_global_attn_indices)\n # get value vectors for global only\n value_vectors_only_global = value_vectors.new_zeros(\n batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim\n )\n value_vectors_only_global[is_local_index_global_attn_nonzero] = value_vectors[is_index_global_attn_nonzero]\n\n # use `matmul` because `einsum` crashes sometimes with fp16\n # attn = torch.einsum('blhs,bshd->blhd', (selected_attn_probs, selected_v))\n # compute attn output only global\n attn_output_only_global = torch.matmul(\n attn_probs_only_global.transpose(1, 2).clone(), value_vectors_only_global.transpose(1, 2).clone()\n ).transpose(1, 2)\n\n # reshape attn probs\n attn_probs_without_global = attn_probs.narrow(\n -1, max_num_global_attn_indices, attn_probs.size(-1) - max_num_global_attn_indices\n ).contiguous()\n\n # compute attn output with global\n attn_output_without_global = self._sliding_chunks_matmul_attn_probs_value(\n attn_probs_without_global, value_vectors, self.one_sided_attn_window_size\n )\n return attn_output_only_global + attn_output_without_global\n\n def _compute_global_attn_output_from_hidden(\n self,\n hidden_states,\n max_num_global_attn_indices,\n layer_head_mask,\n is_local_index_global_attn_nonzero,\n is_index_global_attn_nonzero,\n is_local_index_no_global_attn_nonzero,\n is_index_masked,\n ):\n seq_len, batch_size = hidden_states.shape[:2]\n\n # prepare global hidden states\n global_attn_hidden_states = hidden_states.new_zeros(max_num_global_attn_indices, batch_size, self.embed_dim)\n global_attn_hidden_states[is_local_index_global_attn_nonzero[::-1]] = hidden_states[\n is_index_global_attn_nonzero[::-1]\n ]\n\n # global key, query, value\n global_query_vectors_only_global = self.query_global(global_attn_hidden_states)\n global_key_vectors = self.key_global(hidden_states)\n global_value_vectors = self.value_global(hidden_states)\n\n # normalize\n global_query_vectors_only_global /= math.sqrt(self.head_dim)\n\n # reshape\n global_query_vectors_only_global = (\n global_query_vectors_only_global.contiguous()\n .view(max_num_global_attn_indices, batch_size * self.num_heads, self.head_dim)\n .transpose(0, 1)\n ) # (batch_size * self.num_heads, max_num_global_attn_indices, head_dim)\n global_key_vectors = (\n global_key_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)\n ) # batch_size * self.num_heads, seq_len, head_dim)\n global_value_vectors = (\n global_value_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)\n ) # batch_size * self.num_heads, seq_len, head_dim)\n\n # compute attn scores\n global_attn_scores = torch.bmm(global_query_vectors_only_global, global_key_vectors.transpose(1, 2))\n\n assert list(global_attn_scores.size()) == [\n batch_size * self.num_heads,\n max_num_global_attn_indices,\n seq_len,\n ], (\n \"global_attn_scores have the wrong size. Size should be\"\n f\" {(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)}, but is\"\n f\" {global_attn_scores.size()}.\"\n )\n\n global_attn_scores = global_attn_scores.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)\n\n global_attn_scores[\n is_local_index_no_global_attn_nonzero[0], :, is_local_index_no_global_attn_nonzero[1], :\n ] = torch.finfo(global_attn_scores.dtype).min\n\n global_attn_scores = global_attn_scores.masked_fill(\n is_index_masked[:, None, None, :],\n torch.finfo(global_attn_scores.dtype).min,\n )\n\n global_attn_scores = global_attn_scores.view(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)\n\n # compute global attn probs\n global_attn_probs_float = nn.functional.softmax(\n global_attn_scores, dim=-1, dtype=torch.float32\n ) # use fp32 for numerical stability\n\n # apply layer head masking\n if layer_head_mask is not None:\n assert layer_head_mask.size() == (\n self.num_heads,\n ), f\"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}\"\n global_attn_probs_float = layer_head_mask.view(1, -1, 1, 1) * global_attn_probs_float.view(\n batch_size, self.num_heads, max_num_global_attn_indices, seq_len\n )\n global_attn_probs_float = global_attn_probs_float.view(\n batch_size * self.num_heads, max_num_global_attn_indices, seq_len\n )\n\n global_attn_probs = nn.functional.dropout(\n global_attn_probs_float.type_as(global_attn_scores), p=self.dropout, training=self.training\n )\n\n # global attn output\n global_attn_output = torch.bmm(global_attn_probs, global_value_vectors)\n\n assert list(global_attn_output.size()) == [\n batch_size * self.num_heads,\n max_num_global_attn_indices,\n self.head_dim,\n ], (\n \"global_attn_output tensor has the wrong size. Size should be\"\n f\" {(batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim)}, but is\"\n f\" {global_attn_output.size()}.\"\n )\n\n global_attn_probs = global_attn_probs.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)\n global_attn_output = global_attn_output.view(\n batch_size, self.num_heads, max_num_global_attn_indices, self.head_dim\n )\n return global_attn_output, global_attn_probs\n\n\n# Copied from transformers.models.bert.modeling_bert.BertSelfOutput\nclass LongformerSelfOutput(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass LongformerAttention(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.self = LongformerSelfAttention(config, layer_id)\n self.output = LongformerSelfOutput(config)\n self.pruned_heads = set()\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.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads\n )\n\n # Prune linear layers\n self.self.query = prune_linear_layer(self.self.query, index)\n self.self.key = prune_linear_layer(self.self.key, index)\n self.self.value = prune_linear_layer(self.self.value, index)\n self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)\n\n # Update hyper params and store pruned heads\n self.self.num_attention_heads = self.self.num_attention_heads - len(heads)\n self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads\n self.pruned_heads = self.pruned_heads.union(heads)\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n layer_head_mask=None,\n is_index_masked=None,\n is_index_global_attn=None,\n is_global_attn=None,\n output_attentions=False,\n ):\n self_outputs = self.self(\n hidden_states,\n attention_mask=attention_mask,\n layer_head_mask=layer_head_mask,\n is_index_masked=is_index_masked,\n is_index_global_attn=is_index_global_attn,\n is_global_attn=is_global_attn,\n output_attentions=output_attentions,\n )\n attn_output = self.output(self_outputs[0], hidden_states)\n outputs = (attn_output,) + self_outputs[1:]\n return outputs\n\n\n# Copied from transformers.models.bert.modeling_bert.BertIntermediate\nclass LongformerIntermediate(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.bert.modeling_bert.BertOutput\nclass LongformerOutput(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass LongformerLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.attention = LongformerAttention(config, layer_id)\n self.intermediate = LongformerIntermediate(config)\n self.output = LongformerOutput(config)\n self.chunk_size_feed_forward = config.chunk_size_feed_forward\n self.seq_len_dim = 1\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n layer_head_mask=None,\n is_index_masked=None,\n is_index_global_attn=None,\n is_global_attn=None,\n output_attentions=False,\n ):\n self_attn_outputs = self.attention(\n hidden_states,\n attention_mask=attention_mask,\n layer_head_mask=layer_head_mask,\n is_index_masked=is_index_masked,\n is_index_global_attn=is_index_global_attn,\n is_global_attn=is_global_attn,\n output_attentions=output_attentions,\n )\n attn_output = self_attn_outputs[0]\n outputs = self_attn_outputs[1:]\n\n layer_output = apply_chunking_to_forward(\n self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attn_output\n )\n outputs = (layer_output,) + outputs\n return outputs\n\n def ff_chunk(self, attn_output):\n intermediate_output = self.intermediate(attn_output)\n layer_output = self.output(intermediate_output, attn_output)\n return layer_output\n\n\nclass LongformerEncoder(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.layer = nn.ModuleList([LongformerLayer(config, layer_id=i) for i in range(config.num_hidden_layers)])\n self.gradient_checkpointing = False\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n head_mask=None,\n padding_len=0,\n output_attentions=False,\n output_hidden_states=False,\n return_dict=True,\n ):\n\n is_index_masked = attention_mask < 0\n is_index_global_attn = attention_mask > 0\n is_global_attn = is_index_global_attn.flatten().any().item()\n\n all_hidden_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None # All local attentions.\n all_global_attentions = () if (output_attentions and is_global_attn) else None\n\n # check if head_mask has a correct number of layers specified if desired\n if head_mask is not None:\n assert head_mask.size()[0] == (\n len(self.layer)\n ), f\"The head_mask should be specified for {len(self.layer)} layers, but it is for {head_mask.size()[0]}.\"\n for idx, layer_module in enumerate(self.layer):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, is_global_attn, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(layer_module),\n hidden_states,\n attention_mask,\n head_mask[idx] if head_mask is not None else None,\n is_index_masked,\n is_index_global_attn,\n )\n else:\n layer_outputs = layer_module(\n hidden_states,\n attention_mask=attention_mask,\n layer_head_mask=head_mask[idx] if head_mask is not None else None,\n is_index_masked=is_index_masked,\n is_index_global_attn=is_index_global_attn,\n is_global_attn=is_global_attn,\n output_attentions=output_attentions,\n )\n hidden_states = layer_outputs[0]\n\n if output_attentions:\n # bzs x seq_len x num_attn_heads x (num_global_attn + attention_window_len + 1) => bzs x num_attn_heads x seq_len x (num_global_attn + attention_window_len + 1)\n all_attentions = all_attentions + (layer_outputs[1].transpose(1, 2),)\n\n if is_global_attn:\n # bzs x num_attn_heads x num_global_attn x seq_len => bzs x num_attn_heads x seq_len x num_global_attn\n all_global_attentions = all_global_attentions + (layer_outputs[2].transpose(2, 3),)\n\n # Add last layer\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # undo padding\n if padding_len > 0:\n # unpad `hidden_states` because the calling function is expecting a length == input_ids.size(1)\n hidden_states = hidden_states[:, :-padding_len]\n if output_hidden_states:\n all_hidden_states = tuple([state[:, :-padding_len] for state in all_hidden_states])\n\n if output_attentions:\n all_attentions = tuple([state[:, :, :-padding_len, :] for state in all_attentions])\n\n if not return_dict:\n return tuple(\n v for v in [hidden_states, all_hidden_states, all_attentions, all_global_attentions] if v is not None\n )\n return LongformerBaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_attentions,\n global_attentions=all_global_attentions,\n )\n\n\n# Copied from transformers.models.bert.modeling_bert.BertPooler\nclass LongformerPooler(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\n# Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead with Roberta->Longformer\nclass LongformerLMHead(nn.Module):\n \"\"\"Longformer Head for masked language modeling.\"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size)\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n self.decoder.bias = self.bias\n\n def forward(self, features, **kwargs):\n x = self.dense(features)\n x = gelu(x)\n x = self.layer_norm(x)\n\n # project back to size of vocabulary with bias\n x = self.decoder(x)\n\n return x\n\n def _tie_weights(self):\n # To tie those two weights if they get disconnected (on TPU or when the bias is resized)\n self.bias = self.decoder.bias\n\n\nclass LongformerPreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = LongformerConfig\n base_model_prefix = \"longformer\"\n supports_gradient_checkpointing = True\n _keys_to_ignore_on_load_missing = [r\"position_ids\"]\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights\"\"\"\n if isinstance(module, nn.Linear):\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 module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.Embedding):\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, LongformerEncoder):\n module.gradient_checkpointing = value\n\n\nLONGFORMER_START_DOCSTRING = r\"\"\"\n\n This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n etc.)\n\n This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n and behavior.\n\n Parameters:\n config ([`LongformerConfig`]): Model configuration class with all the parameters of the\n model. Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\nLONGFORMER_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (`torch.LongTensor` of shape `({0})`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`LongformerTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n global_attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):\n Mask to decide the attention given on each token, local attention or global attention. Tokens with global\n attention attends to all other tokens, and all other tokens attend to them. This is important for\n task-specific finetuning because it makes the model more flexible at representing the task. For example,\n for classification, the <s> token should be given global attention. For QA, all question tokens should also\n have global attention. Please refer to the [Longformer paper](https://arxiv.org/abs/2004.05150) for more\n details. Mask values selected in `[0, 1]`:\n\n - 0 for local attention (a sliding window attention),\n - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).\n\n head_mask (`torch.Tensor` of shape `(num_layers, num_heads)`, *optional*):\n Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n decoder_head_mask (`torch.Tensor` of shape `(num_layers, num_heads)`, *optional*):\n Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):\n Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,\n 1]`:\n\n - 0 corresponds to a *sentence A* token,\n - 1 corresponds to a *sentence B* token.\n\n [What are token type IDs?](../glossary#token-type-ids)\n position_ids (`torch.LongTensor` of shape `({0})`, *optional*):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n config.max_position_embeddings - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n model's internal embedding lookup matrix.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare Longformer Model outputting raw hidden-states without any specific head on top.\",\n LONGFORMER_START_DOCSTRING,\n)\nclass LongformerModel(LongformerPreTrainedModel):\n \"\"\"\n This class copied code from [`RobertaModel`] and overwrote standard self-attention with longformer self-attention\n to provide the ability to process long sequences following the self-attention approach described in [Longformer:\n the Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, and Arman Cohan.\n Longformer self-attention combines a local (sliding window) and global attention to extend to long documents\n without the O(n^2) increase in memory and compute.\n\n The self-attention module `LongformerSelfAttention` implemented here supports the combination of local and global\n attention but it lacks support for autoregressive attention and dilated attention. Autoregressive and dilated\n attention are more relevant for autoregressive language modeling than finetuning on downstream tasks. Future\n release will add support for autoregressive attention, but the support for dilated attention requires a custom CUDA\n kernel to be memory and compute efficient.\n\n \"\"\"\n\n def __init__(self, config, add_pooling_layer=True):\n super().__init__(config)\n self.config = config\n\n if isinstance(config.attention_window, int):\n assert config.attention_window % 2 == 0, \"`config.attention_window` has to be an even value\"\n assert config.attention_window > 0, \"`config.attention_window` has to be positive\"\n config.attention_window = [config.attention_window] * config.num_hidden_layers # one value per layer\n else:\n assert len(config.attention_window) == config.num_hidden_layers, (\n \"`len(config.attention_window)` should equal `config.num_hidden_layers`. \"\n f\"Expected {config.num_hidden_layers}, given {len(config.attention_window)}\"\n )\n\n self.embeddings = LongformerEmbeddings(config)\n self.encoder = LongformerEncoder(config)\n self.pooler = LongformerPooler(config) if add_pooling_layer else None\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_input_embeddings(self):\n return self.embeddings.word_embeddings\n\n def set_input_embeddings(self, value):\n self.embeddings.word_embeddings = value\n\n def _prune_heads(self, heads_to_prune):\n \"\"\"\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n \"\"\"\n for layer, heads in heads_to_prune.items():\n self.encoder.layer[layer].attention.prune_heads(heads)\n\n def _pad_to_window_size(\n self,\n input_ids: torch.Tensor,\n attention_mask: torch.Tensor,\n token_type_ids: torch.Tensor,\n position_ids: torch.Tensor,\n inputs_embeds: torch.Tensor,\n pad_token_id: int,\n ):\n \"\"\"A helper function to pad tokens and mask to work with implementation of Longformer self-attention.\"\"\"\n # padding\n attention_window = (\n self.config.attention_window\n if isinstance(self.config.attention_window, int)\n else max(self.config.attention_window)\n )\n\n assert attention_window % 2 == 0, f\"`attention_window` should be an even value. Given {attention_window}\"\n input_shape = input_ids.shape if input_ids is not None else inputs_embeds.shape\n batch_size, seq_len = input_shape[:2]\n\n padding_len = (attention_window - seq_len % attention_window) % attention_window\n if padding_len > 0:\n logger.info(\n f\"Input ids are automatically padded from {seq_len} to {seq_len + padding_len} to be a multiple of \"\n f\"`config.attention_window`: {attention_window}\"\n )\n if input_ids is not None:\n input_ids = nn.functional.pad(input_ids, (0, padding_len), value=pad_token_id)\n if position_ids is not None:\n # pad with position_id = pad_token_id as in modeling_roberta.RobertaEmbeddings\n position_ids = nn.functional.pad(position_ids, (0, padding_len), value=pad_token_id)\n if inputs_embeds is not None:\n input_ids_padding = inputs_embeds.new_full(\n (batch_size, padding_len),\n self.config.pad_token_id,\n dtype=torch.long,\n )\n inputs_embeds_padding = self.embeddings(input_ids_padding)\n inputs_embeds = torch.cat([inputs_embeds, inputs_embeds_padding], dim=-2)\n\n attention_mask = nn.functional.pad(\n attention_mask, (0, padding_len), value=False\n ) # no attention on the padding tokens\n token_type_ids = nn.functional.pad(token_type_ids, (0, padding_len), value=0) # pad with token_type_id = 0\n\n return padding_len, input_ids, attention_mask, token_type_ids, position_ids, inputs_embeds\n\n def _merge_to_attention_mask(self, attention_mask: torch.Tensor, global_attention_mask: torch.Tensor):\n # longformer self attention expects attention mask to have 0 (no attn), 1 (local attn), 2 (global attn)\n # (global_attention_mask + 1) => 1 for local attention, 2 for global attention\n # => final attention_mask => 0 for no attention, 1 for local attention 2 for global attention\n if attention_mask is not None:\n attention_mask = attention_mask * (global_attention_mask + 1)\n else:\n # simply use `global_attention_mask` as `attention_mask`\n # if no `attention_mask` is given\n attention_mask = global_attention_mask + 1\n return attention_mask\n\n @add_start_docstrings_to_model_forward(LONGFORMER_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=LongformerBaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n global_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LongformerBaseModelOutputWithPooling]:\n r\"\"\"\n\n Returns:\n\n Examples:\n\n ```python\n >>> import torch\n >>> from transformers import LongformerModel, LongformerTokenizer\n\n >>> model = LongformerModel.from_pretrained(\"allenai/longformer-base-4096\")\n >>> tokenizer = LongformerTokenizer.from_pretrained(\"allenai/longformer-base-4096\")\n\n >>> SAMPLE_TEXT = \" \".join([\"Hello world! \"] * 1000) # long input document\n >>> input_ids = torch.tensor(tokenizer.encode(SAMPLE_TEXT)).unsqueeze(0) # batch of size 1\n\n >>> attention_mask = torch.ones(\n ... input_ids.shape, dtype=torch.long, device=input_ids.device\n ... ) # initialize to local attention\n >>> global_attention_mask = torch.zeros(\n ... input_ids.shape, dtype=torch.long, device=input_ids.device\n ... ) # initialize to global attention to be deactivated for all tokens\n >>> global_attention_mask[\n ... :,\n ... [\n ... 1,\n ... 4,\n ... 21,\n ... ],\n ... ] = 1 # Set global attention to random tokens for the sake of this example\n >>> # Usually, set global attention based on the task. For example,\n >>> # classification: the <s> token\n >>> # QA: question tokens\n >>> # LM: potentially on the beginning of sentences and paragraphs\n >>> outputs = model(input_ids, attention_mask=attention_mask, global_attention_mask=global_attention_mask)\n >>> sequence_output = outputs.last_hidden_state\n >>> pooled_output = outputs.pooler_output\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\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(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n if attention_mask is None:\n attention_mask = torch.ones(input_shape, device=device)\n if token_type_ids is None:\n token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)\n\n # merge `global_attention_mask` and `attention_mask`\n if global_attention_mask is not None:\n attention_mask = self._merge_to_attention_mask(attention_mask, global_attention_mask)\n\n padding_len, input_ids, attention_mask, token_type_ids, position_ids, inputs_embeds = self._pad_to_window_size(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n inputs_embeds=inputs_embeds,\n pad_token_id=self.config.pad_token_id,\n )\n\n # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]\n # ourselves in which case we just need to make it broadcastable to all heads.\n extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)[\n :, 0, 0, :\n ]\n\n embedding_output = self.embeddings(\n input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds\n )\n\n encoder_outputs = self.encoder(\n embedding_output,\n attention_mask=extended_attention_mask,\n head_mask=head_mask,\n padding_len=padding_len,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output) if self.pooler is not None else None\n\n if not return_dict:\n return (sequence_output, pooled_output) + encoder_outputs[1:]\n\n return LongformerBaseModelOutputWithPooling(\n last_hidden_state=sequence_output,\n pooler_output=pooled_output,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n global_attentions=encoder_outputs.global_attentions,\n )\n\n\n@add_start_docstrings(\"\"\"Longformer Model with a `language modeling` head on top.\"\"\", LONGFORMER_START_DOCSTRING)\nclass LongformerForMaskedLM(LongformerPreTrainedModel):\n\n _keys_to_ignore_on_load_unexpected = [r\"pooler\"]\n\n def __init__(self, config):\n super().__init__(config)\n\n self.longformer = LongformerModel(config, add_pooling_layer=False)\n self.lm_head = LongformerLMHead(config)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_output_embeddings(self):\n return self.lm_head.decoder\n\n def set_output_embeddings(self, new_embeddings):\n self.lm_head.decoder = new_embeddings\n\n @add_start_docstrings_to_model_forward(LONGFORMER_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=LongformerMaskedLMOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n global_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LongformerMaskedLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n kwargs (`Dict[str, any]`, optional, defaults to *{}*):\n Used to hide legacy arguments that have been deprecated.\n\n Returns:\n\n Mask filling example:\n\n ```python\n >>> from transformers import LongformerTokenizer, LongformerForMaskedLM\n\n >>> tokenizer = LongformerTokenizer.from_pretrained(\"allenai/longformer-base-4096\")\n >>> model = LongformerForMaskedLM.from_pretrained(\"allenai/longformer-base-4096\")\n ```\n\n Let's try a very long input.\n\n ```python\n >>> TXT = (\n ... \"My friends are <mask> but they eat too many carbs.\"\n ... + \" That's why I decide not to eat with them.\" * 300\n ... )\n >>> input_ids = tokenizer([TXT], return_tensors=\"pt\")[\"input_ids\"]\n >>> logits = model(input_ids).logits\n\n >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()\n >>> probs = logits[0, masked_index].softmax(dim=0)\n >>> values, predictions = probs.topk(5)\n\n >>> tokenizer.decode(predictions).split()\n ['healthy', 'skinny', 'thin', 'good', 'vegetarian']\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.longformer(\n input_ids,\n attention_mask=attention_mask,\n global_attention_mask=global_attention_mask,\n head_mask=head_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n sequence_output = outputs[0]\n prediction_scores = self.lm_head(sequence_output)\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n return LongformerMaskedLMOutput(\n loss=masked_lm_loss,\n logits=prediction_scores,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n global_attentions=outputs.global_attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n Longformer Model transformer with a sequence classification/regression head on top (a linear layer on top of the\n pooled output) e.g. for GLUE tasks.\n \"\"\",\n LONGFORMER_START_DOCSTRING,\n)\nclass LongformerForSequenceClassification(LongformerPreTrainedModel):\n\n _keys_to_ignore_on_load_unexpected = [r\"pooler\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n self.config = config\n\n self.longformer = LongformerModel(config, add_pooling_layer=False)\n self.classifier = LongformerClassificationHead(config)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(LONGFORMER_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"jpelhaw/longformer-base-plagiarism-detection\",\n output_type=LongformerSequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n expected_output=\"'ORIGINAL'\",\n expected_loss=5.44,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n global_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LongformerSequenceClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if global_attention_mask is None:\n logger.info(\"Initializing global attention on CLS token...\")\n global_attention_mask = torch.zeros_like(input_ids)\n # global attention on cls token\n global_attention_mask[:, 0] = 1\n\n outputs = self.longformer(\n input_ids,\n attention_mask=attention_mask,\n global_attention_mask=global_attention_mask,\n head_mask=head_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n sequence_output = outputs[0]\n logits = self.classifier(sequence_output)\n\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n\n if not return_dict:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return LongformerSequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n global_attentions=outputs.global_attentions,\n )\n\n\nclass LongformerClassificationHead(nn.Module):\n \"\"\"Head for sentence-level classification tasks.\"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.out_proj = nn.Linear(config.hidden_size, config.num_labels)\n\n def forward(self, hidden_states, **kwargs):\n hidden_states = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.dense(hidden_states)\n hidden_states = torch.tanh(hidden_states)\n hidden_states = self.dropout(hidden_states)\n output = self.out_proj(hidden_states)\n return output\n\n\n@add_start_docstrings(\n \"\"\"\n Longformer Model with a span classification head on top for extractive question-answering tasks like SQuAD /\n TriviaQA (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n \"\"\",\n LONGFORMER_START_DOCSTRING,\n)\nclass LongformerForQuestionAnswering(LongformerPreTrainedModel):\n\n _keys_to_ignore_on_load_unexpected = [r\"pooler\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.longformer = LongformerModel(config, add_pooling_layer=False)\n self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(LONGFORMER_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=LongformerQuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n global_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n start_positions: Optional[torch.Tensor] = None,\n end_positions: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LongformerQuestionAnsweringModelOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import LongformerTokenizer, LongformerForQuestionAnswering\n >>> import torch\n\n >>> tokenizer = LongformerTokenizer.from_pretrained(\"allenai/longformer-large-4096-finetuned-triviaqa\")\n >>> model = LongformerForQuestionAnswering.from_pretrained(\"allenai/longformer-large-4096-finetuned-triviaqa\")\n\n >>> question, text = \"Who was Jim Henson?\", \"Jim Henson was a nice puppet\"\n >>> encoding = tokenizer(question, text, return_tensors=\"pt\")\n >>> input_ids = encoding[\"input_ids\"]\n\n >>> # default is local attention everywhere\n >>> # the forward method will automatically set global attention on question tokens\n >>> attention_mask = encoding[\"attention_mask\"]\n\n >>> outputs = model(input_ids, attention_mask=attention_mask)\n >>> start_logits = outputs.start_logits\n >>> end_logits = outputs.end_logits\n >>> all_tokens = tokenizer.convert_ids_to_tokens(input_ids[0].tolist())\n\n >>> answer_tokens = all_tokens[torch.argmax(start_logits) : torch.argmax(end_logits) + 1]\n >>> answer = tokenizer.decode(\n ... tokenizer.convert_tokens_to_ids(answer_tokens)\n ... ) # remove space prepending space token\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if global_attention_mask is None:\n if input_ids is None:\n logger.warning(\n \"It is not possible to automatically generate the `global_attention_mask` because input_ids is\"\n \" None. Please make sure that it is correctly set.\"\n )\n else:\n # set global attention on question tokens automatically\n global_attention_mask = _compute_global_attention_mask(input_ids, self.config.sep_token_id)\n\n outputs = self.longformer(\n input_ids,\n attention_mask=attention_mask,\n global_attention_mask=global_attention_mask,\n head_mask=head_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + outputs[2:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return LongformerQuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n global_attentions=outputs.global_attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n Longformer Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.\n for Named-Entity-Recognition (NER) tasks.\n \"\"\",\n LONGFORMER_START_DOCSTRING,\n)\nclass LongformerForTokenClassification(LongformerPreTrainedModel):\n\n _keys_to_ignore_on_load_unexpected = [r\"pooler\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.longformer = LongformerModel(config, add_pooling_layer=False)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(LONGFORMER_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"brad1141/Longformer-finetuned-norm\",\n output_type=LongformerTokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n expected_output=(\n \"['Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence',\"\n \" 'Evidence', 'Evidence', 'Evidence', 'Evidence']\"\n ),\n expected_loss=0.63,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n global_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LongformerTokenClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.longformer(\n input_ids,\n attention_mask=attention_mask,\n global_attention_mask=global_attention_mask,\n head_mask=head_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return LongformerTokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n global_attentions=outputs.global_attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n Longformer Model with a multiple choice classification head on top (a linear layer on top of the pooled output and\n a softmax) e.g. for RocStories/SWAG tasks.\n \"\"\",\n LONGFORMER_START_DOCSTRING,\n)\nclass LongformerForMultipleChoice(LongformerPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.longformer = LongformerModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, 1)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(\n LONGFORMER_INPUTS_DOCSTRING.format(\"batch_size, num_choices, sequence_length\")\n )\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=LongformerMultipleChoiceModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n global_attention_mask: Optional[torch.Tensor] = None,\n head_mask: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, LongformerMultipleChoiceModelOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,\n num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See\n `input_ids` above)\n \"\"\"\n num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # set global attention on question tokens\n if global_attention_mask is None and input_ids is not None:\n logger.info(\"Initializing global attention on multiple choice...\")\n # put global attention on all tokens after `config.sep_token_id`\n global_attention_mask = torch.stack(\n [\n _compute_global_attention_mask(input_ids[:, i], self.config.sep_token_id, before_sep_token=False)\n for i in range(num_choices)\n ],\n dim=1,\n )\n\n flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None\n flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None\n flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None\n flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None\n flat_global_attention_mask = (\n global_attention_mask.view(-1, global_attention_mask.size(-1))\n if global_attention_mask is not None\n else None\n )\n flat_inputs_embeds = (\n inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))\n if inputs_embeds is not None\n else None\n )\n\n outputs = self.longformer(\n flat_input_ids,\n position_ids=flat_position_ids,\n token_type_ids=flat_token_type_ids,\n attention_mask=flat_attention_mask,\n global_attention_mask=flat_global_attention_mask,\n head_mask=head_mask,\n inputs_embeds=flat_inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n reshaped_logits = logits.view(-1, num_choices)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n\n if not return_dict:\n output = (reshaped_logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return LongformerMultipleChoiceModelOutput(\n loss=loss,\n logits=reshaped_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n global_attentions=outputs.global_attentions,\n )\n", "# coding=utf-8\n# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\n PyTorch XLM model.\n\"\"\"\n\nimport itertools\nimport math\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\n\nfrom ...activations import gelu\nfrom ...modeling_outputs import (\n BaseModelOutput,\n MaskedLMOutput,\n MultipleChoiceModelOutput,\n QuestionAnsweringModelOutput,\n SequenceClassifierOutput,\n TokenClassifierOutput,\n)\nfrom ...modeling_utils import PreTrainedModel, SequenceSummary, SQuADHead\nfrom ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer\nfrom ...utils import (\n ModelOutput,\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n logging,\n replace_return_docstrings,\n)\nfrom .configuration_xlm import XLMConfig\n\n\nlogger = logging.get_logger(__name__)\n\n_CHECKPOINT_FOR_DOC = \"xlm-mlm-en-2048\"\n_CONFIG_FOR_DOC = \"XLMConfig\"\n_TOKENIZER_FOR_DOC = \"XLMTokenizer\"\n\nXLM_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"xlm-mlm-en-2048\",\n \"xlm-mlm-ende-1024\",\n \"xlm-mlm-enfr-1024\",\n \"xlm-mlm-enro-1024\",\n \"xlm-mlm-tlm-xnli15-1024\",\n \"xlm-mlm-xnli15-1024\",\n \"xlm-clm-enfr-1024\",\n \"xlm-clm-ende-1024\",\n \"xlm-mlm-17-1280\",\n \"xlm-mlm-100-1280\",\n # See all XLM models at https://huggingface.co/models?filter=xlm\n]\n\n\ndef create_sinusoidal_embeddings(n_pos, dim, out):\n position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])\n out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))\n out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))\n out.detach_()\n out.requires_grad = False\n\n\ndef get_masks(slen, lengths, causal, padding_mask=None):\n \"\"\"\n Generate hidden states mask, and optionally an attention mask.\n \"\"\"\n alen = torch.arange(slen, dtype=torch.long, device=lengths.device)\n if padding_mask is not None:\n mask = padding_mask\n else:\n assert lengths.max().item() <= slen\n mask = alen < lengths[:, None]\n\n # attention mask is the same as mask, or triangular inferior attention (causal)\n bs = lengths.size(0)\n if causal:\n attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]\n else:\n attn_mask = mask\n\n # sanity check\n assert mask.size() == (bs, slen)\n assert causal is False or attn_mask.size() == (bs, slen, slen)\n\n return mask, attn_mask\n\n\nclass MultiHeadAttention(nn.Module):\n\n NEW_ID = itertools.count()\n\n def __init__(self, n_heads, dim, config):\n super().__init__()\n self.layer_id = next(MultiHeadAttention.NEW_ID)\n self.dim = dim\n self.n_heads = n_heads\n self.dropout = config.attention_dropout\n assert self.dim % self.n_heads == 0\n\n self.q_lin = nn.Linear(dim, dim)\n self.k_lin = nn.Linear(dim, dim)\n self.v_lin = nn.Linear(dim, dim)\n self.out_lin = nn.Linear(dim, dim)\n self.pruned_heads = set()\n\n def prune_heads(self, heads):\n attention_head_size = self.dim // self.n_heads\n if len(heads) == 0:\n return\n heads, index = find_pruneable_heads_and_indices(heads, self.n_heads, attention_head_size, self.pruned_heads)\n # Prune linear layers\n self.q_lin = prune_linear_layer(self.q_lin, index)\n self.k_lin = prune_linear_layer(self.k_lin, index)\n self.v_lin = prune_linear_layer(self.v_lin, index)\n self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)\n # Update hyper params\n self.n_heads = self.n_heads - len(heads)\n self.dim = attention_head_size * self.n_heads\n self.pruned_heads = self.pruned_heads.union(heads)\n\n def forward(self, input, mask, kv=None, cache=None, head_mask=None, output_attentions=False):\n \"\"\"\n Self-attention (if kv is None) or attention over source sentence (provided by kv).\n \"\"\"\n # Input is (bs, qlen, dim)\n # Mask is (bs, klen) (non-causal) or (bs, klen, klen)\n bs, qlen, dim = input.size()\n if kv is None:\n klen = qlen if cache is None else cache[\"slen\"] + qlen\n else:\n klen = kv.size(1)\n # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'\n n_heads = self.n_heads\n dim_per_head = self.dim // n_heads\n mask_reshape = (bs, 1, qlen, klen) if mask.dim() == 3 else (bs, 1, 1, klen)\n\n def shape(x):\n \"\"\"projection\"\"\"\n return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)\n\n def unshape(x):\n \"\"\"compute context\"\"\"\n return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)\n\n q = shape(self.q_lin(input)) # (bs, n_heads, qlen, dim_per_head)\n if kv is None:\n k = shape(self.k_lin(input)) # (bs, n_heads, qlen, dim_per_head)\n v = shape(self.v_lin(input)) # (bs, n_heads, qlen, dim_per_head)\n elif cache is None or self.layer_id not in cache:\n k = v = kv\n k = shape(self.k_lin(k)) # (bs, n_heads, qlen, dim_per_head)\n v = shape(self.v_lin(v)) # (bs, n_heads, qlen, dim_per_head)\n\n if cache is not None:\n if self.layer_id in cache:\n if kv is None:\n k_, v_ = cache[self.layer_id]\n k = torch.cat([k_, k], dim=2) # (bs, n_heads, klen, dim_per_head)\n v = torch.cat([v_, v], dim=2) # (bs, n_heads, klen, dim_per_head)\n else:\n k, v = cache[self.layer_id]\n cache[self.layer_id] = (k, v)\n\n q = q / math.sqrt(dim_per_head) # (bs, n_heads, qlen, dim_per_head)\n scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, qlen, klen)\n mask = (mask == 0).view(mask_reshape).expand_as(scores) # (bs, n_heads, qlen, klen)\n scores.masked_fill_(mask, torch.finfo(scores.dtype).min) # (bs, n_heads, qlen, klen)\n\n weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores) # (bs, n_heads, qlen, klen)\n weights = nn.functional.dropout(weights, p=self.dropout, training=self.training) # (bs, n_heads, qlen, klen)\n\n # Mask heads if we want to\n if head_mask is not None:\n weights = weights * head_mask\n\n context = torch.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)\n context = unshape(context) # (bs, qlen, dim)\n\n outputs = (self.out_lin(context),)\n if output_attentions:\n outputs = outputs + (weights,)\n return outputs\n\n\nclass TransformerFFN(nn.Module):\n def __init__(self, in_dim, dim_hidden, out_dim, config):\n super().__init__()\n self.dropout = config.dropout\n self.lin1 = nn.Linear(in_dim, dim_hidden)\n self.lin2 = nn.Linear(dim_hidden, out_dim)\n self.act = gelu if config.gelu_activation else nn.functional.relu\n self.chunk_size_feed_forward = config.chunk_size_feed_forward\n self.seq_len_dim = 1\n\n def forward(self, input):\n return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)\n\n def ff_chunk(self, input):\n x = self.lin1(input)\n x = self.act(x)\n x = self.lin2(x)\n x = nn.functional.dropout(x, p=self.dropout, training=self.training)\n return x\n\n\nclass XLMPreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = XLMConfig\n load_tf_weights = None\n base_model_prefix = \"transformer\"\n\n def __init__(self, *inputs, **kwargs):\n super().__init__(*inputs, **kwargs)\n\n @property\n def dummy_inputs(self):\n inputs_list = torch.tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])\n attns_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])\n if self.config.use_lang_emb and self.config.n_langs > 1:\n langs_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])\n else:\n langs_list = None\n return {\"input_ids\": inputs_list, \"attention_mask\": attns_list, \"langs\": langs_list}\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights.\"\"\"\n if isinstance(module, nn.Embedding):\n if self.config is not None and self.config.embed_init_std is not None:\n nn.init.normal_(module.weight, mean=0, std=self.config.embed_init_std)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n if isinstance(module, nn.Linear):\n if self.config is not None and self.config.init_std is not None:\n nn.init.normal_(module.weight, mean=0, std=self.config.init_std)\n if module.bias is not None:\n nn.init.constant_(module.bias, 0.0)\n if isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n\n@dataclass\nclass XLMForQuestionAnsweringOutput(ModelOutput):\n \"\"\"\n Base class for outputs of question answering models using a `SquadHead`.\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):\n Classification loss as the sum of start token, end token (and is_impossible if provided) classification\n losses.\n start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):\n Log probabilities for the top config.start_n_top start token possibilities (beam-search).\n start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):\n Indices for the top config.start_n_top start token possibilities (beam-search).\n end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):\n Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities\n (beam-search).\n end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):\n Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).\n cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):\n Log probabilities for the `is_impossible` label of the answers.\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n start_top_log_probs: Optional[torch.FloatTensor] = None\n start_top_index: Optional[torch.LongTensor] = None\n end_top_log_probs: Optional[torch.FloatTensor] = None\n end_top_index: Optional[torch.LongTensor] = None\n cls_logits: Optional[torch.FloatTensor] = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\nXLM_START_DOCSTRING = r\"\"\"\n\n This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n etc.)\n\n This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n and behavior.\n\n Parameters:\n config ([`XLMConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\nXLM_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (`torch.LongTensor` of shape `({0})`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`XLMTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n langs (`torch.LongTensor` of shape `({0})`, *optional*):\n A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are\n languages ids which can be obtained from the language names by using two conversion mappings provided in\n the configuration of the model (only provided for multilingual models). More precisely, the *language name\n to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the\n *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).\n\n See usage examples detailed in the [multilingual documentation](../multilingual).\n token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):\n Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,\n 1]`:\n\n - 0 corresponds to a *sentence A* token,\n - 1 corresponds to a *sentence B* token.\n\n [What are token type IDs?](../glossary#token-type-ids)\n position_ids (`torch.LongTensor` of shape `({0})`, *optional*):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n config.max_position_embeddings - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Length of each sentence that can be used to avoid performing attention on padding token indices. You can\n also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in\n `[0, ..., input_ids.size(-1)]`.\n cache (`Dict[str, torch.FloatTensor]`, *optional*):\n Dictionary string to `torch.FloatTensor` that contains precomputed hidden states (key and values in the\n attention blocks) as computed by the model (see `cache` output below). Can be used to speed up sequential\n decoding.\n\n The dictionary object will be modified in-place during the forward pass to add newly computed\n hidden-states.\n head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):\n Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n model's internal embedding lookup matrix.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare XLM Model transformer outputting raw hidden-states without any specific head on top.\",\n XLM_START_DOCSTRING,\n)\nclass XLMModel(XLMPreTrainedModel):\n _keys_to_ignore_on_load_missing = [r\"position_ids\"]\n\n def __init__(self, config):\n super().__init__(config)\n\n # encoder / decoder, output layer\n self.is_encoder = config.is_encoder\n self.is_decoder = not config.is_encoder\n if self.is_decoder:\n raise NotImplementedError(\"Currently XLM can only be used as an encoder\")\n # self.with_output = with_output\n self.causal = config.causal\n\n # dictionary / languages\n self.n_langs = config.n_langs\n self.use_lang_emb = config.use_lang_emb\n self.n_words = config.n_words\n self.eos_index = config.eos_index\n self.pad_index = config.pad_index\n # self.dico = dico\n # self.id2lang = config.id2lang\n # self.lang2id = config.lang2id\n # assert len(self.dico) == self.n_words\n # assert len(self.id2lang) == len(self.lang2id) == self.n_langs\n\n # model parameters\n self.dim = config.emb_dim # 512 by default\n self.hidden_dim = self.dim * 4 # 2048 by default\n self.n_heads = config.n_heads # 8 by default\n self.n_layers = config.n_layers\n self.dropout = config.dropout\n self.attention_dropout = config.attention_dropout\n assert self.dim % self.n_heads == 0, \"transformer dim must be a multiple of n_heads\"\n\n # embeddings\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.dim)\n if config.sinusoidal_embeddings:\n create_sinusoidal_embeddings(config.max_position_embeddings, self.dim, out=self.position_embeddings.weight)\n if config.n_langs > 1 and config.use_lang_emb:\n self.lang_embeddings = nn.Embedding(self.n_langs, self.dim)\n self.embeddings = nn.Embedding(self.n_words, self.dim, padding_idx=self.pad_index)\n self.layer_norm_emb = nn.LayerNorm(self.dim, eps=config.layer_norm_eps)\n\n # transformer layers\n self.attentions = nn.ModuleList()\n self.layer_norm1 = nn.ModuleList()\n self.ffns = nn.ModuleList()\n self.layer_norm2 = nn.ModuleList()\n # if self.is_decoder:\n # self.layer_norm15 = nn.ModuleList()\n # self.encoder_attn = nn.ModuleList()\n\n for _ in range(self.n_layers):\n self.attentions.append(MultiHeadAttention(self.n_heads, self.dim, config=config))\n self.layer_norm1.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))\n # if self.is_decoder:\n # self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))\n # self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))\n self.ffns.append(TransformerFFN(self.dim, self.hidden_dim, self.dim, config=config))\n self.layer_norm2.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))\n\n if hasattr(config, \"pruned_heads\"):\n pruned_heads = config.pruned_heads.copy().items()\n config.pruned_heads = {}\n for layer, heads in pruned_heads:\n if self.attentions[int(layer)].n_heads == config.n_heads:\n self.prune_heads({int(layer): list(map(int, heads))})\n\n # Initialize weights and apply final processing\n self.post_init()\n self.register_buffer(\"position_ids\", torch.arange(config.max_position_embeddings).expand((1, -1)))\n\n def get_input_embeddings(self):\n return self.embeddings\n\n def set_input_embeddings(self, new_embeddings):\n self.embeddings = new_embeddings\n\n def _prune_heads(self, heads_to_prune):\n \"\"\"\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n \"\"\"\n for layer, heads in heads_to_prune.items():\n self.attentions[layer].prune_heads(heads)\n\n @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=BaseModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, BaseModelOutput]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\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:\n bs, slen = input_ids.size()\n else:\n bs, slen = inputs_embeds.size()[:-1]\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n if lengths is None:\n if input_ids is not None:\n lengths = (input_ids != self.pad_index).sum(dim=1).long()\n else:\n lengths = torch.tensor([slen] * bs, device=device)\n # mask = input_ids != self.pad_index\n\n # check inputs\n assert lengths.size(0) == bs\n assert lengths.max().item() <= slen\n # input_ids = input_ids.transpose(0, 1) # batch size as dimension 0\n # assert (src_enc is None) == (src_len is None)\n # if src_enc is not None:\n # assert self.is_decoder\n # assert src_enc.size(0) == bs\n\n # generate masks\n mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)\n # if self.is_decoder and src_enc is not None:\n # src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]\n\n # position_ids\n if position_ids is None:\n position_ids = self.position_ids[:, :slen]\n else:\n assert position_ids.size() == (bs, slen) # (slen, bs)\n # position_ids = position_ids.transpose(0, 1)\n\n # langs\n if langs is not None:\n assert langs.size() == (bs, slen) # (slen, bs)\n # langs = langs.transpose(0, 1)\n\n # Prepare head mask if needed\n head_mask = self.get_head_mask(head_mask, self.config.n_layers)\n\n # do not recompute cached elements\n if cache is not None and input_ids is not None:\n _slen = slen - cache[\"slen\"]\n input_ids = input_ids[:, -_slen:]\n position_ids = position_ids[:, -_slen:]\n if langs is not None:\n langs = langs[:, -_slen:]\n mask = mask[:, -_slen:]\n attn_mask = attn_mask[:, -_slen:]\n\n # embeddings\n if inputs_embeds is None:\n inputs_embeds = self.embeddings(input_ids)\n\n tensor = inputs_embeds + self.position_embeddings(position_ids).expand_as(inputs_embeds)\n if langs is not None and self.use_lang_emb and self.n_langs > 1:\n tensor = tensor + self.lang_embeddings(langs)\n if token_type_ids is not None:\n tensor = tensor + self.embeddings(token_type_ids)\n tensor = self.layer_norm_emb(tensor)\n tensor = nn.functional.dropout(tensor, p=self.dropout, training=self.training)\n tensor *= mask.unsqueeze(-1).to(tensor.dtype)\n\n # transformer layers\n hidden_states = () if output_hidden_states else None\n attentions = () if output_attentions else None\n for i in range(self.n_layers):\n if output_hidden_states:\n hidden_states = hidden_states + (tensor,)\n\n # self attention\n attn_outputs = self.attentions[i](\n tensor,\n attn_mask,\n cache=cache,\n head_mask=head_mask[i],\n output_attentions=output_attentions,\n )\n attn = attn_outputs[0]\n if output_attentions:\n attentions = attentions + (attn_outputs[1],)\n attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)\n tensor = tensor + attn\n tensor = self.layer_norm1[i](tensor)\n\n # encoder attention (for decoder only)\n # if self.is_decoder and src_enc is not None:\n # attn = self.encoder_attn[i](tensor, src_mask, kv=src_enc, cache=cache)\n # attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)\n # tensor = tensor + attn\n # tensor = self.layer_norm15[i](tensor)\n\n # FFN\n tensor = tensor + self.ffns[i](tensor)\n tensor = self.layer_norm2[i](tensor)\n tensor *= mask.unsqueeze(-1).to(tensor.dtype)\n\n # Add last hidden state\n if output_hidden_states:\n hidden_states = hidden_states + (tensor,)\n\n # update cache length\n if cache is not None:\n cache[\"slen\"] += tensor.size(1)\n\n # move back sequence length to dimension 0\n # tensor = tensor.transpose(0, 1)\n\n if not return_dict:\n return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)\n return BaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)\n\n\nclass XLMPredLayer(nn.Module):\n \"\"\"\n Prediction layer (cross_entropy or adaptive_softmax).\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.asm = config.asm\n self.n_words = config.n_words\n self.pad_index = config.pad_index\n dim = config.emb_dim\n\n if config.asm is False:\n self.proj = nn.Linear(dim, config.n_words, bias=True)\n else:\n self.proj = nn.AdaptiveLogSoftmaxWithLoss(\n in_features=dim,\n n_classes=config.n_words,\n cutoffs=config.asm_cutoffs,\n div_value=config.asm_div_value,\n head_bias=True, # default is False\n )\n\n def forward(self, x, y=None):\n \"\"\"Compute the loss, and optionally the scores.\"\"\"\n outputs = ()\n if self.asm is False:\n scores = self.proj(x)\n outputs = (scores,) + outputs\n if y is not None:\n loss = nn.functional.cross_entropy(scores.view(-1, self.n_words), y.view(-1), reduction=\"mean\")\n outputs = (loss,) + outputs\n else:\n scores = self.proj.log_prob(x)\n outputs = (scores,) + outputs\n if y is not None:\n _, loss = self.proj(x, y)\n outputs = (loss,) + outputs\n\n return outputs\n\n\n@add_start_docstrings(\n \"\"\"\n The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input\n embeddings).\n \"\"\",\n XLM_START_DOCSTRING,\n)\nclass XLMWithLMHeadModel(XLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.transformer = XLMModel(config)\n self.pred_layer = XLMPredLayer(config)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_output_embeddings(self):\n return self.pred_layer.proj\n\n def set_output_embeddings(self, new_embeddings):\n self.pred_layer.proj = new_embeddings\n\n def prepare_inputs_for_generation(self, input_ids, **kwargs):\n mask_token_id = self.config.mask_token_id\n lang_id = self.config.lang_id\n\n effective_batch_size = input_ids.shape[0]\n mask_token = torch.full((effective_batch_size, 1), mask_token_id, dtype=torch.long, device=input_ids.device)\n input_ids = torch.cat([input_ids, mask_token], dim=1)\n if lang_id is not None:\n langs = torch.full_like(input_ids, lang_id)\n else:\n langs = None\n return {\"input_ids\": input_ids, \"langs\": langs}\n\n @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=MaskedLMOutput,\n config_class=_CONFIG_FOR_DOC,\n mask=\"<special1>\",\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, MaskedLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set\n `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`\n are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`\n \"\"\"\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 attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n output = transformer_outputs[0]\n outputs = self.pred_layer(output, labels) # (loss, logits) or (logits,) depending on if labels are provided.\n\n if not return_dict:\n return outputs + transformer_outputs[1:]\n\n return MaskedLMOutput(\n loss=outputs[0] if labels is not None else None,\n logits=outputs[0] if labels is None else outputs[1],\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.\n for GLUE tasks.\n \"\"\",\n XLM_START_DOCSTRING,\n)\nclass XLMForSequenceClassification(XLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n self.config = config\n\n self.transformer = XLMModel(config)\n self.sequence_summary = SequenceSummary(config)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=SequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, SequenceClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\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 attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n output = transformer_outputs[0]\n logits = self.sequence_summary(output)\n\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n\n if not return_dict:\n output = (logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return SequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n \"\"\",\n XLM_START_DOCSTRING,\n)\nclass XLMForQuestionAnsweringSimple(XLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.transformer = XLMModel(config)\n self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=QuestionAnsweringModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n start_positions: Optional[torch.Tensor] = None,\n end_positions: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, QuestionAnsweringModelOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n \"\"\"\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 attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = transformer_outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + transformer_outputs[1:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return QuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n XLM Model with a beam-search span classification head on top for extractive question-answering tasks like SQuAD (a\n linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n \"\"\",\n XLM_START_DOCSTRING,\n)\nclass XLMForQuestionAnswering(XLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.transformer = XLMModel(config)\n self.qa_outputs = SQuADHead(config)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=XLMForQuestionAnsweringOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n start_positions: Optional[torch.Tensor] = None,\n end_positions: Optional[torch.Tensor] = None,\n is_impossible: Optional[torch.Tensor] = None,\n cls_index: Optional[torch.Tensor] = None,\n p_mask: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, XLMForQuestionAnsweringOutput]:\n r\"\"\"\n start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence\n are not taken into account for computing the loss.\n is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels whether a question has an answer or no answer (SQuAD 2.0)\n cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for position (index) of the classification token to use as input for computing plausibility of the\n answer.\n p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be\n masked. 0.0 mean token is not masked.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import XLMTokenizer, XLMForQuestionAnswering\n >>> import torch\n\n >>> tokenizer = XLMTokenizer.from_pretrained(\"xlm-mlm-en-2048\")\n >>> model = XLMForQuestionAnswering.from_pretrained(\"xlm-mlm-en-2048\")\n\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\", add_special_tokens=True)).unsqueeze(\n ... 0\n ... ) # Batch size 1\n >>> start_positions = torch.tensor([1])\n >>> end_positions = torch.tensor([3])\n\n >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)\n >>> loss = outputs.loss\n ```\"\"\"\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 attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n output = transformer_outputs[0]\n\n outputs = self.qa_outputs(\n output,\n start_positions=start_positions,\n end_positions=end_positions,\n cls_index=cls_index,\n is_impossible=is_impossible,\n p_mask=p_mask,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return outputs + transformer_outputs[1:]\n\n return XLMForQuestionAnsweringOutput(\n loss=outputs.loss,\n start_top_log_probs=outputs.start_top_log_probs,\n start_top_index=outputs.start_top_index,\n end_top_log_probs=outputs.end_top_log_probs,\n end_top_index=outputs.end_top_index,\n cls_logits=outputs.cls_logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n XLM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for\n Named-Entity-Recognition (NER) tasks.\n \"\"\",\n XLM_START_DOCSTRING,\n)\nclass XLMForTokenClassification(XLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.transformer = XLMModel(config)\n self.dropout = nn.Dropout(config.dropout)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, TokenClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n XLM Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a\n softmax) e.g. for RocStories/SWAG tasks.\n \"\"\",\n XLM_START_DOCSTRING,\n)\nclass XLMForMultipleChoice(XLMPreTrainedModel):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.transformer = XLMModel(config)\n self.sequence_summary = SequenceSummary(config)\n self.logits_proj = nn.Linear(config.num_labels, 1)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format(\"batch_size, num_choices, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=MultipleChoiceModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids: Optional[torch.Tensor] = None,\n attention_mask: Optional[torch.Tensor] = None,\n langs: Optional[torch.Tensor] = None,\n token_type_ids: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.Tensor] = None,\n lengths: Optional[torch.Tensor] = None,\n cache: Optional[Dict[str, torch.Tensor]] = None,\n head_mask: Optional[torch.Tensor] = None,\n inputs_embeds: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, MultipleChoiceModelOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,\n num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See\n `input_ids` above)\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]\n\n input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None\n attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None\n token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None\n position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None\n langs = langs.view(-1, langs.size(-1)) if langs is not None else None\n inputs_embeds = (\n inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))\n if inputs_embeds is not None\n else None\n )\n\n if lengths is not None:\n logger.warning(\n \"The `lengths` parameter cannot be used with the XLM multiple choice models. Please use the \"\n \"attention mask instead.\"\n )\n lengths = None\n\n transformer_outputs = self.transformer(\n input_ids=input_ids,\n attention_mask=attention_mask,\n langs=langs,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n lengths=lengths,\n cache=cache,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n output = transformer_outputs[0]\n logits = self.sequence_summary(output)\n logits = self.logits_proj(logits)\n reshaped_logits = logits.view(-1, num_choices)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n\n if not return_dict:\n output = (reshaped_logits,) + transformer_outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return MultipleChoiceModelOutput(\n loss=loss,\n logits=reshaped_logits,\n hidden_states=transformer_outputs.hidden_states,\n attentions=transformer_outputs.attentions,\n )\n", "# coding=utf-8\n# Copyright 2018 LXMERT Authors, The Hugging Face Team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport copy\nimport unittest\n\nimport numpy as np\n\nfrom transformers import LxmertConfig, is_tf_available, is_torch_available\nfrom transformers.models.auto import get_values\nfrom transformers.testing_utils import require_torch, slow, torch_device\n\nfrom ...test_configuration_common import ConfigTester\nfrom ...test_modeling_common import ModelTesterMixin, ids_tensor\n\n\nif is_torch_available():\n import torch\n\n from transformers import (\n MODEL_FOR_PRETRAINING_MAPPING,\n MODEL_FOR_QUESTION_ANSWERING_MAPPING,\n LxmertForPreTraining,\n LxmertForQuestionAnswering,\n LxmertModel,\n )\n from transformers.models.lxmert.modeling_lxmert import LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST\n\n\nif is_tf_available():\n import tensorflow as tf\n\n\nclass LxmertModelTester:\n def __init__(\n self,\n parent,\n vocab_size=300,\n hidden_size=28,\n num_attention_heads=2,\n num_labels=2,\n intermediate_size=64,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n num_qa_labels=30,\n num_object_labels=16,\n num_attr_labels=4,\n num_visual_features=10,\n l_layers=2,\n x_layers=1,\n r_layers=1,\n visual_feat_dim=128,\n visual_pos_dim=4,\n visual_loss_normalizer=6.67,\n seq_length=20,\n batch_size=4,\n is_training=True,\n task_matched=True,\n task_mask_lm=True,\n task_obj_predict=True,\n task_qa=True,\n visual_obj_loss=True,\n visual_attr_loss=True,\n visual_feat_loss=True,\n use_token_type_ids=True,\n use_lang_mask=True,\n output_attentions=False,\n output_hidden_states=False,\n scope=None,\n ):\n self.parent = parent\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.num_labels = num_labels\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.pad_token_id = pad_token_id\n self.num_qa_labels = num_qa_labels\n self.num_object_labels = num_object_labels\n self.num_attr_labels = num_attr_labels\n self.l_layers = l_layers\n self.x_layers = x_layers\n self.r_layers = r_layers\n self.visual_feat_dim = visual_feat_dim\n self.visual_pos_dim = visual_pos_dim\n self.visual_loss_normalizer = visual_loss_normalizer\n self.seq_length = seq_length\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_lang_mask = use_lang_mask\n self.task_matched = task_matched\n self.task_mask_lm = task_mask_lm\n self.task_obj_predict = task_obj_predict\n self.task_qa = task_qa\n self.visual_obj_loss = visual_obj_loss\n self.visual_attr_loss = visual_attr_loss\n self.visual_feat_loss = visual_feat_loss\n self.num_visual_features = num_visual_features\n self.use_token_type_ids = use_token_type_ids\n self.output_attentions = output_attentions\n self.output_hidden_states = output_hidden_states\n self.scope = scope\n self.num_hidden_layers = {\"vision\": r_layers, \"cross_encoder\": x_layers, \"language\": l_layers}\n\n def prepare_config_and_inputs(self):\n\n output_attentions = self.output_attentions\n input_ids = ids_tensor([self.batch_size, self.seq_length], vocab_size=self.vocab_size)\n visual_feats = torch.rand(self.batch_size, self.num_visual_features, self.visual_feat_dim, device=torch_device)\n bounding_boxes = torch.rand(self.batch_size, self.num_visual_features, 4, device=torch_device)\n\n input_mask = None\n if self.use_lang_mask:\n input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)\n token_type_ids = None\n if self.use_token_type_ids:\n token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)\n obj_labels = None\n if self.task_obj_predict:\n obj_labels = {}\n if self.visual_attr_loss and self.task_obj_predict:\n obj_labels[\"attr\"] = (\n ids_tensor([self.batch_size, self.num_visual_features], self.num_attr_labels),\n ids_tensor([self.batch_size, self.num_visual_features], self.num_attr_labels),\n )\n if self.visual_feat_loss and self.task_obj_predict:\n obj_labels[\"feat\"] = (\n ids_tensor(\n [self.batch_size, self.num_visual_features, self.visual_feat_dim], self.num_visual_features\n ),\n ids_tensor([self.batch_size, self.num_visual_features], self.num_visual_features),\n )\n if self.visual_obj_loss and self.task_obj_predict:\n obj_labels[\"obj\"] = (\n ids_tensor([self.batch_size, self.num_visual_features], self.num_object_labels),\n ids_tensor([self.batch_size, self.num_visual_features], self.num_object_labels),\n )\n ans = None\n if self.task_qa:\n ans = ids_tensor([self.batch_size], self.num_qa_labels)\n masked_lm_labels = None\n if self.task_mask_lm:\n masked_lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n matched_label = None\n if self.task_matched:\n matched_label = ids_tensor([self.batch_size], self.num_labels)\n\n config = self.get_config()\n\n return (\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n )\n\n def get_config(self):\n return LxmertConfig(\n vocab_size=self.vocab_size,\n hidden_size=self.hidden_size,\n num_attention_heads=self.num_attention_heads,\n num_labels=self.num_labels,\n intermediate_size=self.intermediate_size,\n hidden_act=self.hidden_act,\n hidden_dropout_prob=self.hidden_dropout_prob,\n attention_probs_dropout_prob=self.attention_probs_dropout_prob,\n max_position_embeddings=self.max_position_embeddings,\n type_vocab_size=self.type_vocab_size,\n initializer_range=self.initializer_range,\n layer_norm_eps=self.layer_norm_eps,\n pad_token_id=self.pad_token_id,\n num_qa_labels=self.num_qa_labels,\n num_object_labels=self.num_object_labels,\n num_attr_labels=self.num_attr_labels,\n l_layers=self.l_layers,\n x_layers=self.x_layers,\n r_layers=self.r_layers,\n visual_feat_dim=self.visual_feat_dim,\n visual_pos_dim=self.visual_pos_dim,\n visual_loss_normalizer=self.visual_loss_normalizer,\n task_matched=self.task_matched,\n task_mask_lm=self.task_mask_lm,\n task_obj_predict=self.task_obj_predict,\n task_qa=self.task_qa,\n visual_obj_loss=self.visual_obj_loss,\n visual_attr_loss=self.visual_attr_loss,\n visual_feat_loss=self.visual_feat_loss,\n output_attentions=self.output_attentions,\n output_hidden_states=self.output_hidden_states,\n )\n\n def create_and_check_lxmert_model(\n self,\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ):\n model = LxmertModel(config=config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n output_attentions=output_attentions,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n output_attentions=not output_attentions,\n )\n result = model(input_ids, visual_feats, bounding_boxes, return_dict=False)\n result = model(input_ids, visual_feats, bounding_boxes, return_dict=True)\n\n self.parent.assertEqual(result.language_output.shape, (self.batch_size, self.seq_length, self.hidden_size))\n self.parent.assertEqual(\n result.vision_output.shape, (self.batch_size, self.num_visual_features, self.hidden_size)\n )\n self.parent.assertEqual(result.pooled_output.shape, (self.batch_size, self.hidden_size))\n\n def create_and_check_lxmert_for_question_answering(\n self,\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ):\n model = LxmertForQuestionAnswering(config=config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n labels=ans,\n output_attentions=output_attentions,\n )\n result = model(input_ids, visual_feats, bounding_boxes, labels=ans)\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n labels=ans,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n output_attentions=output_attentions,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n labels=ans,\n output_attentions=not output_attentions,\n )\n\n self.parent.assertEqual(result.question_answering_score.shape, (self.batch_size, self.num_qa_labels))\n\n def create_and_check_lxmert_for_pretraining(\n self,\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ):\n model = LxmertForPreTraining(config=config)\n model.to(torch_device)\n model.eval()\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n obj_labels=obj_labels,\n matched_label=matched_label,\n ans=ans,\n output_attentions=output_attentions,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n output_attentions=not output_attentions,\n return_dict=False,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n obj_labels=obj_labels,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n matched_label=matched_label,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n ans=ans,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n obj_labels=obj_labels,\n matched_label=matched_label,\n ans=ans,\n output_attentions=not output_attentions,\n )\n\n self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size))\n\n def resize_lxmert_num_qa_labels(\n self,\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ):\n\n start_labels = config.num_qa_labels\n num_large_labels = config.num_qa_labels * 2\n num_small_labels = int(config.num_qa_labels * 2)\n less_labels_ans = ids_tensor([self.batch_size], num_small_labels)\n more_labels_ans = ids_tensor([self.batch_size], num_large_labels)\n model_pretrain = LxmertForPreTraining(config=config).to(torch_device)\n model_qa = LxmertForQuestionAnswering(config=config).to(torch_device)\n config.num_labels = num_small_labels\n end_labels = config.num_labels\n\n result_pretrain = model_pretrain(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n ans=ans,\n )\n\n result_qa = model_qa(\n input_ids,\n visual_feats,\n bounding_boxes,\n labels=ans,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n )\n\n model_pretrain.resize_num_qa_labels(num_small_labels)\n model_qa.resize_num_qa_labels(num_small_labels)\n\n result_pretrain_less = model_pretrain(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n ans=less_labels_ans,\n )\n\n result_qa_less = model_qa(\n input_ids,\n visual_feats,\n bounding_boxes,\n labels=less_labels_ans,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n )\n\n model_pretrain.resize_num_qa_labels(num_large_labels)\n model_qa.resize_num_qa_labels(num_large_labels)\n\n result_pretrain_more = model_pretrain(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n ans=more_labels_ans,\n )\n\n result_qa_more = model_qa(\n input_ids,\n visual_feats,\n bounding_boxes,\n labels=more_labels_ans,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n )\n\n model_qa_labels = model_qa.num_qa_labels\n\n self.parent.assertNotEqual(start_labels, end_labels)\n self.parent.assertNotEqual(model_qa_labels, start_labels)\n self.parent.assertEqual(result_qa.question_answering_score.shape, (self.batch_size, start_labels))\n self.parent.assertEqual(result_pretrain.question_answering_score.shape, (self.batch_size, start_labels))\n self.parent.assertEqual(result_qa_less.question_answering_score.shape, (self.batch_size, num_small_labels))\n self.parent.assertEqual(\n result_pretrain_less.question_answering_score.shape, (self.batch_size, num_small_labels)\n )\n self.parent.assertEqual(result_qa_more.question_answering_score.shape, (self.batch_size, num_large_labels))\n self.parent.assertEqual(\n result_pretrain_more.question_answering_score.shape, (self.batch_size, num_large_labels)\n )\n\n def prepare_config_and_inputs_for_common(self, return_obj_labels=False):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ) = config_and_inputs\n\n inputs_dict = {\n \"input_ids\": input_ids,\n \"visual_feats\": visual_feats,\n \"visual_pos\": bounding_boxes,\n \"token_type_ids\": token_type_ids,\n \"attention_mask\": input_mask,\n }\n\n if return_obj_labels:\n inputs_dict[\"obj_labels\"] = obj_labels\n else:\n config.task_obj_predict = False\n\n return config, inputs_dict\n\n\n@require_torch\nclass LxmertModelTest(ModelTesterMixin, unittest.TestCase):\n\n all_model_classes = (LxmertModel, LxmertForPreTraining, LxmertForQuestionAnswering) if is_torch_available() else ()\n\n fx_compatible = True\n test_head_masking = False\n test_pruning = False\n test_torchscript = False\n\n # overwrite function because qa models takes different input label shape\n def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):\n inputs_dict = copy.deepcopy(inputs_dict)\n\n if return_labels:\n if model_class in get_values(MODEL_FOR_QUESTION_ANSWERING_MAPPING):\n inputs_dict[\"labels\"] = torch.zeros(\n self.model_tester.batch_size, dtype=torch.long, device=torch_device\n )\n elif model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):\n # special case for models like BERT that use multi-loss training for PreTraining\n inputs_dict[\"labels\"] = torch.zeros(\n (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device\n )\n return inputs_dict\n\n def setUp(self):\n self.model_tester = LxmertModelTester(self)\n self.config_tester = ConfigTester(self, config_class=LxmertConfig, hidden_size=37)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_lxmert_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_lxmert_model(*config_and_inputs)\n\n def test_lxmert_question_answering(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_lxmert_for_question_answering(*config_and_inputs)\n\n def test_lxmert_pretraining(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_lxmert_for_pretraining(*config_and_inputs)\n\n def test_lxmert_question_answering_labels_resize(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.resize_lxmert_num_qa_labels(*config_and_inputs)\n\n @slow\n def test_model_from_pretrained(self):\n for model_name in LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\n model = LxmertModel.from_pretrained(model_name)\n model.to(torch_device)\n self.assertIsNotNone(model)\n\n def test_attention_outputs(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n seq_len = getattr(self.model_tester, \"seq_length\", None)\n encoder_seq_length = getattr(self.model_tester, \"encoder_seq_length\", seq_len)\n encoder_key_length = getattr(self.model_tester, \"key_length\", encoder_seq_length)\n chunk_length = getattr(self.model_tester, \"chunk_length\", None)\n if chunk_length is not None and hasattr(self.model_tester, \"num_hashes\"):\n encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes\n\n for model_class in self.all_model_classes:\n inputs_dict[\"output_attentions\"] = True\n inputs_dict[\"output_hidden_states\"] = False\n model = model_class(config)\n model.to(torch_device)\n model.eval()\n with torch.no_grad():\n outputs = model(**self._prepare_for_class(inputs_dict, model_class))\n\n language_attentions, vision_attentions, cross_encoder_attentions = (outputs[-3], outputs[-2], outputs[-1])\n\n self.assertEqual(len(language_attentions), self.model_tester.num_hidden_layers[\"language\"])\n self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers[\"vision\"])\n self.assertEqual(len(cross_encoder_attentions), self.model_tester.num_hidden_layers[\"cross_encoder\"])\n\n # check that output_attentions also work using config\n del inputs_dict[\"output_attentions\"]\n config.output_attentions = True\n model = model_class(config)\n model.to(torch_device)\n model.eval()\n with torch.no_grad():\n outputs = model(**self._prepare_for_class(inputs_dict, model_class))\n\n language_attentions, vision_attentions, cross_encoder_attentions = (outputs[-3], outputs[-2], outputs[-1])\n self.assertEqual(len(language_attentions), self.model_tester.num_hidden_layers[\"language\"])\n self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers[\"vision\"])\n self.assertEqual(len(cross_encoder_attentions), self.model_tester.num_hidden_layers[\"cross_encoder\"])\n\n attentions = [language_attentions, vision_attentions, cross_encoder_attentions]\n attention_shapes = [\n [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],\n [\n self.model_tester.num_attention_heads,\n self.model_tester.num_visual_features,\n self.model_tester.num_visual_features,\n ],\n [self.model_tester.num_attention_heads, encoder_key_length, self.model_tester.num_visual_features],\n ]\n\n for attention, attention_shape in zip(attentions, attention_shapes):\n self.assertListEqual(list(attention[0].shape[-3:]), attention_shape)\n out_len = len(outputs)\n\n # Check attention is always last and order is fine\n inputs_dict[\"output_attentions\"] = True\n inputs_dict[\"output_hidden_states\"] = True\n model = model_class(config)\n model.to(torch_device)\n model.eval()\n with torch.no_grad():\n outputs = model(**self._prepare_for_class(inputs_dict, model_class))\n\n # 2 hidden states were added\n self.assertEqual(out_len + 2, len(outputs))\n\n language_attentions, vision_attentions, cross_encoder_attentions = (outputs[-3], outputs[-2], outputs[-1])\n self.assertEqual(len(language_attentions), self.model_tester.num_hidden_layers[\"language\"])\n self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers[\"vision\"])\n self.assertEqual(len(cross_encoder_attentions), self.model_tester.num_hidden_layers[\"cross_encoder\"])\n\n attentions = [language_attentions, vision_attentions, cross_encoder_attentions]\n attention_shapes = [\n [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],\n [\n self.model_tester.num_attention_heads,\n self.model_tester.num_visual_features,\n self.model_tester.num_visual_features,\n ],\n [self.model_tester.num_attention_heads, encoder_key_length, self.model_tester.num_visual_features],\n ]\n\n for attention, attention_shape in zip(attentions, attention_shapes):\n self.assertListEqual(list(attention[0].shape[-3:]), attention_shape)\n\n def test_hidden_states_output(self):\n def check_hidden_states_output(inputs_dict, config, model_class):\n model = model_class(config)\n model.to(torch_device)\n model.eval()\n\n with torch.no_grad():\n outputs = model(**self._prepare_for_class(inputs_dict, model_class))\n language_hidden_states, vision_hidden_states = outputs[-2], outputs[-1]\n\n self.assertEqual(len(language_hidden_states), self.model_tester.num_hidden_layers[\"language\"] + 1)\n self.assertEqual(len(vision_hidden_states), self.model_tester.num_hidden_layers[\"vision\"] + 1)\n\n seq_length = self.model_tester.seq_length\n num_visual_features = self.model_tester.num_visual_features\n\n self.assertListEqual(\n list(language_hidden_states[0].shape[-2:]),\n [seq_length, self.model_tester.hidden_size],\n )\n self.assertListEqual(\n list(vision_hidden_states[0].shape[-2:]),\n [num_visual_features, self.model_tester.hidden_size],\n )\n\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n\n for model_class in self.all_model_classes:\n inputs_dict[\"output_hidden_states\"] = True\n check_hidden_states_output(inputs_dict, config, model_class)\n\n # check that output_hidden_states also work using config\n del inputs_dict[\"output_hidden_states\"]\n config.output_hidden_states = True\n\n check_hidden_states_output(inputs_dict, config, model_class)\n\n def test_retain_grad_hidden_states_attentions(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n config.output_hidden_states = True\n config.output_attentions = True\n\n # no need to test all models as different heads yield the same functionality\n model_class = self.all_model_classes[0]\n model = model_class(config)\n model.to(torch_device)\n\n inputs = self._prepare_for_class(inputs_dict, model_class)\n\n outputs = model(**inputs)\n\n hidden_states_lang = outputs.language_hidden_states[0]\n attentions_lang = outputs.language_attentions[0]\n\n hidden_states_vision = outputs.vision_hidden_states[0]\n attentions_vision = outputs.vision_attentions[0]\n\n hidden_states_lang.retain_grad()\n attentions_lang.retain_grad()\n hidden_states_vision.retain_grad()\n attentions_vision.retain_grad()\n\n outputs.language_output.flatten()[0].backward(retain_graph=True)\n outputs.vision_output.flatten()[0].backward(retain_graph=True)\n\n self.assertIsNotNone(hidden_states_lang.grad)\n self.assertIsNotNone(attentions_vision.grad)\n self.assertIsNotNone(hidden_states_vision.grad)\n self.assertIsNotNone(attentions_vision.grad)\n\n def prepare_tf_inputs_from_pt_inputs(self, pt_inputs_dict):\n\n tf_inputs_dict = {}\n for key, value in pt_inputs_dict.items():\n # skip key that does not exist in tf\n if isinstance(value, dict):\n tf_inputs_dict[key] = self.prepare_pt_inputs_from_tf_inputs(value)\n elif isinstance(value, (list, tuple)):\n tf_inputs_dict[key] = (self.prepare_pt_inputs_from_tf_inputs(iter_value) for iter_value in value)\n elif type(value) == bool:\n tf_inputs_dict[key] = value\n elif key == \"input_values\":\n tf_inputs_dict[key] = tf.convert_to_tensor(value.cpu().numpy(), dtype=tf.float32)\n elif key == \"pixel_values\":\n tf_inputs_dict[key] = tf.convert_to_tensor(value.cpu().numpy(), dtype=tf.float32)\n elif key == \"input_features\":\n tf_inputs_dict[key] = tf.convert_to_tensor(value.cpu().numpy(), dtype=tf.float32)\n # other general float inputs\n elif value.is_floating_point():\n tf_inputs_dict[key] = tf.convert_to_tensor(value.cpu().numpy(), dtype=tf.float32)\n else:\n tf_inputs_dict[key] = tf.convert_to_tensor(value.cpu().numpy(), dtype=tf.int32)\n\n return tf_inputs_dict\n\n\n@require_torch\nclass LxmertModelIntegrationTest(unittest.TestCase):\n @slow\n def test_inference_no_head_absolute_embedding(self):\n model = LxmertModel.from_pretrained(LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST[0])\n input_ids = torch.tensor([[101, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 102]])\n num_visual_features = 10\n _, visual_feats = np.random.seed(0), np.random.rand(1, num_visual_features, model.config.visual_feat_dim)\n _, visual_pos = np.random.seed(0), np.random.rand(1, num_visual_features, 4)\n visual_feats = torch.as_tensor(visual_feats, dtype=torch.float32)\n visual_pos = torch.as_tensor(visual_pos, dtype=torch.float32)\n output = model(input_ids, visual_feats=visual_feats, visual_pos=visual_pos)[0]\n expected_shape = torch.Size([1, 11, 768])\n self.assertEqual(expected_shape, output.shape)\n expected_slice = torch.tensor(\n [[[0.2417, -0.9807, 0.1480], [1.2541, -0.8320, 0.5112], [1.4070, -1.1052, 0.6990]]]\n )\n\n self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))\n", "# coding=utf-8\n# Copyright 2022 The Fairseq Authors and the HuggingFace Inc. team. 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 Wav2Vec2-Conformer model.\"\"\"\n\nimport math\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torch.utils.checkpoint\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss\n\nfrom ...activations import ACT2FN\nfrom ...deepspeed import is_deepspeed_zero3_enabled\nfrom ...modeling_outputs import (\n BaseModelOutput,\n CausalLMOutput,\n SequenceClassifierOutput,\n TokenClassifierOutput,\n Wav2Vec2BaseModelOutput,\n XVectorOutput,\n)\nfrom ...modeling_utils import PreTrainedModel\nfrom ...pytorch_utils import torch_int_div\nfrom ...utils import (\n ModelOutput,\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n logging,\n replace_return_docstrings,\n)\nfrom .configuration_wav2vec2_conformer import Wav2Vec2ConformerConfig\n\n\nlogger = logging.get_logger(__name__)\n\n\n_HIDDEN_STATES_START_POSITION = 2\n\n# General docstring\n_CONFIG_FOR_DOC = \"Wav2Vec2ConformerConfig\"\n_PROCESSOR_FOR_DOC = \"Wav2Vec2Processor\"\n\n# Base docstring\n_CHECKPOINT_FOR_DOC = \"facebook/wav2vec2-conformer-rope-large-960h-ft\"\n_EXPECTED_OUTPUT_SHAPE = [1, 292, 1024]\n\n# CTC docstring\n_CTC_EXPECTED_OUTPUT = \"'MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL'\"\n_CTC_EXPECTED_LOSS = 64.21\n\n# Audio class docstring\n_FEAT_EXTRACTOR_FOR_DOC = \"Wav2Vec2FeatureExtractor\"\n_SEQ_CLASS_CHECKPOINT = \"hf-internal-testing/wav2vec2-conformer-seq-class\"\n_SEQ_CLASS_EXPECTED_OUTPUT = \"'LABEL_0'\"\n_SEQ_CLASS_EXPECTED_LOSS = 0.68\n\n# Frame class docstring\n_FRAME_CLASS_CHECKPOINT = \"hf-internal-testing/wav2vec2-conformer-frame-class\"\n_FRAME_EXPECTED_OUTPUT = [1, 0]\n\n# Speaker Verification docstring\n_XVECTOR_CHECKPOINT = \"hf-internal-testing/wav2vec2-conformer-xvector\"\n_XVECTOR_EXPECTED_OUTPUT = 1.0\n\n\nWAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"facebook/wav2vec2-conformer-large-rel-pos\",\n # See all Wav2Vec2Conformer models at https://huggingface.co/models?filter=wav2vec2-conformer\n]\n\n\n@dataclass\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTrainingOutput with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerForPreTrainingOutput(ModelOutput):\n \"\"\"\n Output type of [`Wav2Vec2ConformerForPreTraining`], with potential hidden states and attentions.\n\n Args:\n loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):\n Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official\n paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.\n projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):\n Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked\n projected quantized states.\n projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):\n Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive\n target vectors for contrastive loss.\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n contrastive_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):\n The contrastive loss (L_m) as stated in the [official paper](https://arxiv.org/pdf/2006.11477.pdf) .\n diversity_loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):\n The diversity loss (L_d) as stated in the [official paper](https://arxiv.org/pdf/2006.11477.pdf) .\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n projected_states: torch.FloatTensor = None\n projected_quantized_states: torch.FloatTensor = None\n codevector_perplexity: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n contrastive_loss: Optional[torch.FloatTensor] = None\n diversity_loss: Optional[torch.FloatTensor] = None\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2._compute_mask_indices\ndef _compute_mask_indices(\n shape: Tuple[int, int],\n mask_prob: float,\n mask_length: int,\n attention_mask: Optional[torch.LongTensor] = None,\n min_masks: int = 0,\n) -> np.ndarray:\n \"\"\"\n Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for\n ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on\n CPU as part of the preprocessing during training.\n\n Args:\n shape: The shape for which to compute masks. This should be of a tuple of size 2 where\n the first element is the batch size and the second element is the length of the axis to span.\n mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of\n independently generated mask spans of length `mask_length` is computed by\n `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the\n actual percentage will be smaller.\n mask_length: size of the mask\n min_masks: minimum number of masked spans\n attention_mask: A (right-padded) attention mask which independently shortens the feature axis of\n each batch dimension.\n \"\"\"\n batch_size, sequence_length = shape\n\n if mask_length < 1:\n raise ValueError(\"`mask_length` has to be bigger than 0.\")\n\n if mask_length > sequence_length:\n raise ValueError(\n f\"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}\"\n f\" and `sequence_length`: {sequence_length}`\"\n )\n\n # epsilon is used for probabilistic rounding\n epsilon = np.random.rand(1).item()\n\n def compute_num_masked_span(input_length):\n \"\"\"Given input length, compute how many spans should be masked\"\"\"\n num_masked_span = int(mask_prob * input_length / mask_length + epsilon)\n num_masked_span = max(num_masked_span, min_masks)\n\n # make sure num masked span <= sequence_length\n if num_masked_span * mask_length > sequence_length:\n num_masked_span = sequence_length // mask_length\n\n # make sure num_masked span is also <= input_length - (mask_length - 1)\n if input_length - (mask_length - 1) < num_masked_span:\n num_masked_span = max(input_length - (mask_length - 1), 0)\n\n return num_masked_span\n\n # compute number of masked spans in batch\n input_lengths = (\n attention_mask.sum(-1).detach().tolist()\n if attention_mask is not None\n else [sequence_length for _ in range(batch_size)]\n )\n\n # SpecAugment mask to fill\n spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=np.bool)\n spec_aug_mask_idxs = []\n\n max_num_masked_span = compute_num_masked_span(sequence_length)\n\n if max_num_masked_span == 0:\n return spec_aug_mask\n\n for input_length in input_lengths:\n # compute num of masked spans for this input\n num_masked_span = compute_num_masked_span(input_length)\n\n # get random indices to mask\n spec_aug_mask_idx = np.random.choice(\n np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False\n )\n\n # pick first sampled index that will serve as a dummy index to pad vector\n # to ensure same dimension for all batches due to probabilistic rounding\n # Picking first sample just pads those vectors twice.\n if len(spec_aug_mask_idx) == 0:\n # this case can only happen if `input_length` is strictly smaller then\n # `sequence_length` in which case the last token has to be a padding\n # token which we can use as a dummy mask id\n dummy_mask_idx = sequence_length - 1\n else:\n dummy_mask_idx = spec_aug_mask_idx[0]\n\n spec_aug_mask_idx = np.concatenate(\n [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]\n )\n spec_aug_mask_idxs.append(spec_aug_mask_idx)\n\n spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)\n\n # expand masked indices to masked spans\n spec_aug_mask_idxs = np.broadcast_to(\n spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)\n )\n spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)\n\n # add offset to the starting indexes so that that indexes now create a span\n offsets = np.arange(mask_length)[None, None, :]\n offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(\n batch_size, max_num_masked_span * mask_length\n )\n spec_aug_mask_idxs = spec_aug_mask_idxs + offsets\n\n # ensure that we cannot have indices larger than sequence_length\n if spec_aug_mask_idxs.max() > sequence_length - 1:\n spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1\n\n # scatter indices to mask\n np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)\n\n return spec_aug_mask\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2._sample_negative_indices\ndef _sample_negative_indices(\n features_shape: Tuple, num_negatives: int, mask_time_indices: Optional[np.ndarray] = None\n):\n \"\"\"\n Sample `num_negatives` vectors from feature vectors.\n \"\"\"\n batch_size, sequence_length = features_shape\n\n # generate indices of the positive vectors themselves, repeat them `num_negatives` times\n sequence_length_range = np.arange(sequence_length)\n\n # get `num_negatives` random vector indices from the same utterance\n sampled_negative_indices = np.zeros(shape=(batch_size, sequence_length, num_negatives), dtype=np.int32)\n\n mask_time_indices = (\n mask_time_indices.astype(np.bool) if mask_time_indices is not None else np.ones(features_shape, dtype=np.bool)\n )\n\n for batch_idx in range(batch_size):\n high = mask_time_indices[batch_idx].sum() - 1\n mapped_masked_indices = sequence_length_range[mask_time_indices[batch_idx]]\n\n feature_indices = np.broadcast_to(np.arange(high + 1)[:, None], (high + 1, num_negatives))\n sampled_indices = np.random.randint(0, high, size=(high + 1, num_negatives))\n # avoid sampling the same positive vector, but keep the distribution uniform\n sampled_indices[sampled_indices >= feature_indices] += 1\n\n # remap to actual indices\n sampled_negative_indices[batch_idx][mask_time_indices[batch_idx]] = mapped_masked_indices[sampled_indices]\n\n # correct for batch size\n sampled_negative_indices[batch_idx] += batch_idx * sequence_length\n\n return sampled_negative_indices\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2NoLayerNormConvLayer with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerNoLayerNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2LayerNormConvLayer with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerLayerNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n\n hidden_states = hidden_states.transpose(-2, -1)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = hidden_states.transpose(-2, -1)\n\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2GroupNormConvLayer with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerGroupNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.activation = ACT2FN[config.feat_extract_activation]\n\n self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2PositionalConvEmbedding with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerPositionalConvEmbedding(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.conv = nn.Conv1d(\n config.hidden_size,\n config.hidden_size,\n kernel_size=config.num_conv_pos_embeddings,\n padding=config.num_conv_pos_embeddings // 2,\n groups=config.num_conv_pos_embedding_groups,\n )\n\n if is_deepspeed_zero3_enabled():\n import deepspeed\n\n with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):\n self.conv = nn.utils.weight_norm(self.conv, name=\"weight\", dim=2)\n deepspeed.zero.register_external_parameter(self, self.conv.weight_v)\n deepspeed.zero.register_external_parameter(self, self.conv.weight_g)\n else:\n self.conv = nn.utils.weight_norm(self.conv, name=\"weight\", dim=2)\n\n self.padding = Wav2Vec2ConformerSamePadLayer(config.num_conv_pos_embeddings)\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = hidden_states.transpose(1, 2)\n\n hidden_states = self.conv(hidden_states)\n hidden_states = self.padding(hidden_states)\n hidden_states = self.activation(hidden_states)\n\n hidden_states = hidden_states.transpose(1, 2)\n return hidden_states\n\n\nclass Wav2Vec2ConformerRotaryPositionalEmbedding(nn.Module):\n \"\"\"Rotary positional embedding\n Reference : https://blog.eleuther.ai/rotary-embeddings/ Paper: https://arxiv.org/pdf/2104.09864.pdf\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n dim = config.hidden_size // config.num_attention_heads\n base = config.rotary_embedding_base\n\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))\n self.register_buffer(\"inv_freq\", inv_freq)\n self.cached_sequence_length = None\n self.cached_rotary_positional_embedding = None\n\n def forward(self, hidden_states):\n sequence_length = hidden_states.shape[1]\n\n if sequence_length == self.cached_sequence_length and self.cached_rotary_positional_embedding is not None:\n return self.cached_rotary_positional_embedding\n\n self.cached_sequence_length = sequence_length\n time_stamps = torch.arange(sequence_length).type_as(self.inv_freq)\n freqs = torch.einsum(\"i,j->ij\", time_stamps, self.inv_freq)\n embeddings = torch.cat((freqs, freqs), dim=-1)\n\n cos_embeddings = embeddings.cos()[:, None, None, :]\n sin_embeddings = embeddings.sin()[:, None, None, :]\n self.cached_rotary_positional_embedding = torch.stack([cos_embeddings, sin_embeddings])\n return self.cached_rotary_positional_embedding\n\n\nclass Wav2Vec2ConformerRelPositionalEmbedding(nn.Module):\n \"\"\"Relative positional encoding module.\"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.max_len = config.max_source_positions\n self.d_model = config.hidden_size\n self.pe = None\n self.extend_pe(torch.tensor(0.0).expand(1, self.max_len))\n\n def extend_pe(self, x):\n # Reset the positional encodings\n if self.pe is not None:\n # self.pe contains both positive and negative parts\n # the length of self.pe is 2 * input_len - 1\n if self.pe.size(1) >= x.size(1) * 2 - 1:\n if self.pe.dtype != x.dtype or self.pe.device != x.device:\n self.pe = self.pe.to(dtype=x.dtype, device=x.device)\n return\n # Suppose `i` is the position of query vector and `j` is the\n # position of key vector. We use positive relative positions when keys\n # are to the left (i>j) and negative relative positions otherwise (i<j).\n pe_positive = torch.zeros(x.size(1), self.d_model)\n pe_negative = torch.zeros(x.size(1), self.d_model)\n position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)\n div_term = torch.exp(\n torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model)\n )\n pe_positive[:, 0::2] = torch.sin(position * div_term)\n pe_positive[:, 1::2] = torch.cos(position * div_term)\n pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)\n pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)\n\n # Reverse the order of positive indices and concat both positive and\n # negative indices. This is used to support the shifting trick\n # as in https://arxiv.org/abs/1901.02860\n pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)\n pe_negative = pe_negative[1:].unsqueeze(0)\n pe = torch.cat([pe_positive, pe_negative], dim=1)\n self.pe = pe.to(device=x.device, dtype=x.dtype)\n\n def forward(self, hidden_states: torch.Tensor):\n self.extend_pe(hidden_states)\n start_idx = self.pe.size(1) // 2 - hidden_states.size(1) + 1\n end_idx = self.pe.size(1) // 2 + hidden_states.size(1)\n relative_position_embeddings = self.pe[:, start_idx:end_idx]\n\n return relative_position_embeddings\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2SamePadLayer with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerSamePadLayer(nn.Module):\n def __init__(self, num_conv_pos_embeddings):\n super().__init__()\n self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0\n\n def forward(self, hidden_states):\n if self.num_pad_remove > 0:\n hidden_states = hidden_states[:, :, : -self.num_pad_remove]\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureEncoder with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerFeatureEncoder(nn.Module):\n \"\"\"Construct the features from raw audio waveform\"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n if config.feat_extract_norm == \"group\":\n conv_layers = [Wav2Vec2ConformerGroupNormConvLayer(config, layer_id=0)] + [\n Wav2Vec2ConformerNoLayerNormConvLayer(config, layer_id=i + 1)\n for i in range(config.num_feat_extract_layers - 1)\n ]\n elif config.feat_extract_norm == \"layer\":\n conv_layers = [\n Wav2Vec2ConformerLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)\n ]\n else:\n raise ValueError(\n f\"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']\"\n )\n self.conv_layers = nn.ModuleList(conv_layers)\n self.gradient_checkpointing = False\n self._requires_grad = True\n\n def _freeze_parameters(self):\n for param in self.parameters():\n param.requires_grad = False\n self._requires_grad = False\n\n def forward(self, input_values):\n hidden_states = input_values[:, None]\n\n # make sure hidden_states require grad for gradient_checkpointing\n if self._requires_grad and self.training:\n hidden_states.requires_grad = True\n\n for conv_layer in self.conv_layers:\n if self._requires_grad and self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs)\n\n return custom_forward\n\n hidden_states = torch.utils.checkpoint.checkpoint(\n create_custom_forward(conv_layer),\n hidden_states,\n )\n else:\n hidden_states = conv_layer(hidden_states)\n\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureProjection with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerFeatureProjection(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)\n self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)\n self.dropout = nn.Dropout(config.feat_proj_dropout)\n\n def forward(self, hidden_states):\n # non-projected hidden states are needed for quantization\n norm_hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.projection(norm_hidden_states)\n hidden_states = self.dropout(hidden_states)\n return hidden_states, norm_hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeedForward with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerFeedForward(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.intermediate_dropout = nn.Dropout(config.activation_dropout)\n\n self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.output_dropout = nn.Dropout(config.hidden_dropout)\n\n def forward(self, hidden_states):\n hidden_states = self.intermediate_dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n hidden_states = self.intermediate_dropout(hidden_states)\n\n hidden_states = self.output_dense(hidden_states)\n hidden_states = self.output_dropout(hidden_states)\n return hidden_states\n\n\nclass Wav2Vec2ConformerConvolutionModule(nn.Module):\n \"\"\"Convolution block used in the conformer block\"\"\"\n\n def __init__(self, config):\n super().__init__()\n if (config.conv_depthwise_kernel_size - 1) % 2 == 1:\n raise ValueError(\"`config.conv_depthwise_kernel_size` should be a odd number for 'SAME' padding\")\n self.layer_norm = nn.LayerNorm(config.hidden_size)\n self.pointwise_conv1 = torch.nn.Conv1d(\n config.hidden_size,\n 2 * config.hidden_size,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n )\n self.glu = torch.nn.GLU(dim=1)\n self.depthwise_conv = torch.nn.Conv1d(\n config.hidden_size,\n config.hidden_size,\n config.conv_depthwise_kernel_size,\n stride=1,\n padding=(config.conv_depthwise_kernel_size - 1) // 2,\n groups=config.hidden_size,\n bias=False,\n )\n self.batch_norm = torch.nn.BatchNorm1d(config.hidden_size)\n self.activation = ACT2FN[config.hidden_act]\n self.pointwise_conv2 = torch.nn.Conv1d(\n config.hidden_size,\n config.hidden_size,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n )\n self.dropout = torch.nn.Dropout(config.conformer_conv_dropout)\n\n def forward(self, hidden_states):\n hidden_states = self.layer_norm(hidden_states)\n # exchange the temporal dimension and the feature dimension\n hidden_states = hidden_states.transpose(1, 2)\n\n # GLU mechanism\n # => (batch, 2*channel, dim)\n hidden_states = self.pointwise_conv1(hidden_states)\n # => (batch, channel, dim)\n hidden_states = self.glu(hidden_states)\n\n # 1D Depthwise Conv\n hidden_states = self.depthwise_conv(hidden_states)\n hidden_states = self.batch_norm(hidden_states)\n hidden_states = self.activation(hidden_states)\n\n hidden_states = self.pointwise_conv2(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = hidden_states.transpose(1, 2)\n return hidden_states\n\n\nclass Wav2Vec2ConformerSelfAttention(nn.Module):\n \"\"\"Construct an Wav2Vec2ConformerSelfAttention object.\n Can be enhanced with rotary or relative position embeddings.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n self.head_size = config.hidden_size // config.num_attention_heads\n self.num_heads = config.num_attention_heads\n self.position_embeddings_type = config.position_embeddings_type\n\n self.linear_q = nn.Linear(config.hidden_size, config.hidden_size)\n self.linear_k = nn.Linear(config.hidden_size, config.hidden_size)\n self.linear_v = nn.Linear(config.hidden_size, config.hidden_size)\n self.linear_out = nn.Linear(config.hidden_size, config.hidden_size)\n\n self.dropout = nn.Dropout(p=config.attention_dropout)\n\n if self.position_embeddings_type == \"relative\":\n # linear transformation for positional encoding\n self.linear_pos = nn.Linear(config.hidden_size, config.hidden_size, bias=False)\n # these two learnable bias are used in matrix c and matrix d\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n self.pos_bias_u = nn.Parameter(torch.Tensor(self.num_heads, self.head_size))\n self.pos_bias_v = nn.Parameter(torch.Tensor(self.num_heads, self.head_size))\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n relative_position_embeddings: Optional[torch.Tensor] = None,\n output_attentions: bool = False,\n ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n # self-attention mechanism\n batch_size, sequence_length, hidden_size = hidden_states.size()\n\n # make sure query/key states can be != value states\n query_key_states = hidden_states\n value_states = hidden_states\n\n if self.position_embeddings_type == \"rotary\":\n if relative_position_embeddings is None:\n raise ValueError(\n \"`relative_position_embeddings` has to be defined when `self.position_embeddings_type == 'rotary'\"\n )\n query_key_states = self._apply_rotary_embedding(query_key_states, relative_position_embeddings)\n\n # project query_key_states and value_states\n query = self.linear_q(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)\n key = self.linear_k(query_key_states).view(batch_size, -1, self.num_heads, self.head_size)\n value = self.linear_v(value_states).view(batch_size, -1, self.num_heads, self.head_size)\n\n # => (batch, head, time1, d_k)\n query = query.transpose(1, 2)\n key = key.transpose(1, 2)\n value = value.transpose(1, 2)\n\n if self.position_embeddings_type == \"relative\":\n if relative_position_embeddings is None:\n raise ValueError(\n \"`relative_position_embeddings` has to be defined when `self.position_embeddings_type ==\"\n \" 'relative'\"\n )\n # apply relative_position_embeddings to qk scores\n # as proposed in Transformer_XL: https://arxiv.org/abs/1901.02860\n scores = self._apply_relative_embeddings(\n query=query, key=key, relative_position_embeddings=relative_position_embeddings\n )\n else:\n scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.head_size)\n\n # apply attention_mask if necessary\n if attention_mask is not None:\n scores = scores + attention_mask\n\n # => (batch, head, time1, time2)\n probs = torch.softmax(scores, dim=-1)\n probs = self.dropout(probs)\n\n # => (batch, head, time1, d_k)\n hidden_states = torch.matmul(probs, value)\n\n # => (batch, time1, hidden_size)\n hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_size)\n hidden_states = self.linear_out(hidden_states)\n\n return hidden_states, probs\n\n def _apply_rotary_embedding(self, hidden_states, relative_position_embeddings):\n batch_size, sequence_length, hidden_size = hidden_states.size()\n hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads, self.head_size)\n\n cos = relative_position_embeddings[0, :sequence_length, ...]\n sin = relative_position_embeddings[1, :sequence_length, ...]\n\n # rotate hidden_states with rotary embeddings\n hidden_states = hidden_states.transpose(0, 1)\n rotated_states_begin = hidden_states[..., : self.head_size // 2]\n rotated_states_end = hidden_states[..., self.head_size // 2 :]\n rotated_states = torch.cat((-rotated_states_end, rotated_states_begin), dim=rotated_states_begin.ndim - 1)\n hidden_states = (hidden_states * cos) + (rotated_states * sin)\n hidden_states = hidden_states.transpose(0, 1)\n\n hidden_states = hidden_states.view(batch_size, sequence_length, self.num_heads * self.head_size)\n\n return hidden_states\n\n def _apply_relative_embeddings(self, query, key, relative_position_embeddings):\n # 1. project positional embeddings\n # => (batch, head, 2*time1-1, d_k)\n proj_relative_position_embeddings = self.linear_pos(relative_position_embeddings)\n proj_relative_position_embeddings = proj_relative_position_embeddings.view(\n relative_position_embeddings.size(0), -1, self.num_heads, self.head_size\n )\n proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(1, 2)\n proj_relative_position_embeddings = proj_relative_position_embeddings.transpose(2, 3)\n\n # 2. Add bias to query\n # => (batch, head, time1, d_k)\n query = query.transpose(1, 2)\n q_with_bias_u = (query + self.pos_bias_u).transpose(1, 2)\n q_with_bias_v = (query + self.pos_bias_v).transpose(1, 2)\n\n # 3. attention score: first compute matrix a and matrix c\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n # => (batch, head, time1, time2)\n scores_ac = torch.matmul(q_with_bias_u, key.transpose(-2, -1))\n\n # 4. then compute matrix b and matrix d\n # => (batch, head, time1, 2*time1-1)\n scores_bd = torch.matmul(q_with_bias_v, proj_relative_position_embeddings)\n\n # 5. shift matrix b and matrix d\n zero_pad = torch.zeros((*scores_bd.size()[:3], 1), device=scores_bd.device, dtype=scores_bd.dtype)\n scores_bd_padded = torch.cat([zero_pad, scores_bd], dim=-1)\n scores_bd_padded_shape = scores_bd.size()[:2] + (scores_bd.shape[3] + 1, scores_bd.shape[2])\n scores_bd_padded = scores_bd_padded.view(*scores_bd_padded_shape)\n scores_bd = scores_bd_padded[:, :, 1:].view_as(scores_bd)\n scores_bd = scores_bd[:, :, :, : scores_bd.size(-1) // 2 + 1]\n\n # 6. sum matrices\n # => (batch, head, time1, time2)\n scores = (scores_ac + scores_bd) / math.sqrt(self.head_size)\n\n return scores\n\n\nclass Wav2Vec2ConformerEncoderLayer(nn.Module):\n \"\"\"Conformer block based on https://arxiv.org/abs/2005.08100.\"\"\"\n\n def __init__(self, config):\n super().__init__()\n embed_dim = config.hidden_size\n dropout = config.attention_dropout\n\n # Feed-forward 1\n self.ffn1_layer_norm = nn.LayerNorm(embed_dim)\n self.ffn1 = Wav2Vec2ConformerFeedForward(config)\n\n # Self-Attention\n self.self_attn_layer_norm = nn.LayerNorm(embed_dim)\n self.self_attn_dropout = torch.nn.Dropout(dropout)\n self.self_attn = Wav2Vec2ConformerSelfAttention(config)\n\n # Conformer Convolution\n self.conv_module = Wav2Vec2ConformerConvolutionModule(config)\n\n # Feed-forward 2\n self.ffn2_layer_norm = nn.LayerNorm(embed_dim)\n self.ffn2 = Wav2Vec2ConformerFeedForward(config)\n self.final_layer_norm = nn.LayerNorm(embed_dim)\n\n def forward(\n self,\n hidden_states,\n attention_mask: Optional[torch.Tensor] = None,\n relative_position_embeddings: Optional[torch.Tensor] = None,\n output_attentions: bool = False,\n ):\n hidden_states = hidden_states\n\n # 1. Feed-Forward 1 layer\n residual = hidden_states\n hidden_states = self.ffn1_layer_norm(hidden_states)\n hidden_states = self.ffn1(hidden_states)\n hidden_states = hidden_states * 0.5 + residual\n residual = hidden_states\n\n # 2. Self-Attention layer\n hidden_states = self.self_attn_layer_norm(hidden_states)\n hidden_states, attn_weigts = self.self_attn(\n hidden_states=hidden_states,\n attention_mask=attention_mask,\n relative_position_embeddings=relative_position_embeddings,\n output_attentions=output_attentions,\n )\n hidden_states = self.self_attn_dropout(hidden_states)\n hidden_states = hidden_states + residual\n\n # 3. Convolutional Layer\n residual = hidden_states\n hidden_states = self.conv_module(hidden_states)\n hidden_states = residual + hidden_states\n\n # 4. Feed-Forward 2 Layer\n residual = hidden_states\n hidden_states = self.ffn2_layer_norm(hidden_states)\n hidden_states = self.ffn2(hidden_states)\n hidden_states = hidden_states * 0.5 + residual\n hidden_states = self.final_layer_norm(hidden_states)\n\n return hidden_states, attn_weigts\n\n\nclass Wav2Vec2ConformerEncoder(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n\n if config.position_embeddings_type == \"relative\":\n self.embed_positions = Wav2Vec2ConformerRelPositionalEmbedding(config)\n elif config.position_embeddings_type == \"rotary\":\n self.embed_positions = Wav2Vec2ConformerRotaryPositionalEmbedding(config)\n else:\n self.embed_positions = None\n\n self.pos_conv_embed = Wav2Vec2ConformerPositionalConvEmbedding(config)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layers = nn.ModuleList([Wav2Vec2ConformerEncoderLayer(config) for _ in range(config.num_hidden_layers)])\n self.gradient_checkpointing = False\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n output_attentions=False,\n output_hidden_states=False,\n return_dict=True,\n ):\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n\n if attention_mask is not None:\n # make sure padded tokens output 0\n hidden_states[~attention_mask] = 0.0\n\n # extend attention_mask\n attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)\n attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min\n attention_mask = attention_mask.expand(\n attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]\n )\n\n hidden_states = self.dropout(hidden_states)\n\n if self.embed_positions is not None:\n relative_position_embeddings = self.embed_positions(hidden_states)\n else:\n relative_position_embeddings = None\n\n deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()\n\n for i, layer in enumerate(self.layers):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = np.random.uniform(0, 1)\n\n skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False\n if not skip_the_layer or deepspeed_zero3_is_enabled:\n # under deepspeed zero3 all gpus must run in sync\n if self.gradient_checkpointing and self.training:\n # create gradient checkpointing function\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(layer),\n hidden_states,\n attention_mask,\n relative_position_embeddings,\n )\n else:\n layer_outputs = layer(\n hidden_states,\n attention_mask=attention_mask,\n relative_position_embeddings=relative_position_embeddings,\n output_attentions=output_attentions,\n )\n hidden_states = layer_outputs[0]\n\n if skip_the_layer:\n layer_outputs = (None, None)\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n\n hidden_states = self.layer_norm(hidden_states)\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)\n return BaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n )\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2GumbelVectorQuantizer with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerGumbelVectorQuantizer(nn.Module):\n \"\"\"\n Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH\n GUMBEL-SOFTMAX](https://arxiv.org/pdf/1611.01144.pdf) for more information.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.num_groups = config.num_codevector_groups\n self.num_vars = config.num_codevectors_per_group\n\n if config.codevector_dim % self.num_groups != 0:\n raise ValueError(\n f\"`config.codevector_dim {config.codevector_dim} must be divisible \"\n f\"by `config.num_codevector_groups` {self.num_groups} for concatenation\"\n )\n\n # storage for codebook variables (codewords)\n self.codevectors = nn.Parameter(\n torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)\n )\n self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)\n\n # can be decayed for training\n self.temperature = 2\n\n @staticmethod\n def _compute_perplexity(probs, mask=None):\n if mask is not None:\n mask_extended = mask.flatten()[:, None, None].expand(probs.shape)\n probs = torch.where(mask_extended, probs, torch.zeros_like(probs))\n marginal_probs = probs.sum(dim=0) / mask.sum()\n else:\n marginal_probs = probs.mean(dim=0)\n\n perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()\n return perplexity\n\n def forward(self, hidden_states, mask_time_indices=None):\n batch_size, sequence_length, hidden_size = hidden_states.shape\n\n # project to codevector dim\n hidden_states = self.weight_proj(hidden_states)\n hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)\n\n if self.training:\n # sample code vector probs via gumbel in differentiateable way\n codevector_probs = nn.functional.gumbel_softmax(\n hidden_states.float(), tau=self.temperature, hard=True\n ).type_as(hidden_states)\n\n # compute perplexity\n codevector_soft_dist = torch.softmax(\n hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1\n )\n perplexity = self._compute_perplexity(codevector_soft_dist, mask_time_indices)\n else:\n # take argmax in non-differentiable way\n # comptute hard codevector distribution (one hot)\n codevector_idx = hidden_states.argmax(dim=-1)\n codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(\n -1, codevector_idx.view(-1, 1), 1.0\n )\n codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)\n\n perplexity = self._compute_perplexity(codevector_probs, mask_time_indices)\n\n codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)\n # use probs to retrieve codevectors\n codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors\n codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)\n codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)\n\n return codevectors, perplexity\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Adapter with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerAdapter(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n # feature dim might need to be down-projected\n if config.output_hidden_size != config.hidden_size:\n self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)\n self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)\n else:\n self.proj = self.proj_layer_norm = None\n\n self.layers = nn.ModuleList(Wav2Vec2ConformerAdapterLayer(config) for _ in range(config.num_adapter_layers))\n self.layerdrop = config.layerdrop\n\n def forward(self, hidden_states):\n # down project hidden_states if necessary\n if self.proj is not None and self.proj_layer_norm is not None:\n hidden_states = self.proj(hidden_states)\n hidden_states = self.proj_layer_norm(hidden_states)\n\n hidden_states = hidden_states.transpose(1, 2)\n\n for layer in self.layers:\n layerdrop_prob = np.random.random()\n if not self.training or (layerdrop_prob > self.layerdrop):\n hidden_states = layer(hidden_states)\n\n hidden_states = hidden_states.transpose(1, 2)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2AdapterLayer with Wav2Vec2->Wav2Vec2Conformer\nclass Wav2Vec2ConformerAdapterLayer(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.conv = nn.Conv1d(\n config.output_hidden_size,\n 2 * config.output_hidden_size,\n config.adapter_kernel_size,\n stride=config.adapter_stride,\n padding=1,\n )\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = nn.functional.glu(hidden_states, dim=1)\n\n return hidden_states\n\n\nclass Wav2Vec2ConformerPreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = Wav2Vec2ConformerConfig\n base_model_prefix = \"wav2vec2_conformer\"\n main_input_name = \"input_values\"\n _keys_to_ignore_on_load_missing = [r\"position_ids\"]\n supports_gradient_checkpointing = True\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights\"\"\"\n # gumbel softmax requires special init\n if isinstance(module, Wav2Vec2ConformerGumbelVectorQuantizer):\n module.weight_proj.weight.data.normal_(mean=0.0, std=1)\n module.weight_proj.bias.data.zero_()\n nn.init.uniform_(module.codevectors)\n elif isinstance(module, Wav2Vec2ConformerSelfAttention):\n if hasattr(module, \"pos_bias_u\"):\n nn.init.xavier_uniform_(module.pos_bias_u)\n if hasattr(module, \"pos_bias_v\"):\n nn.init.xavier_uniform_(module.pos_bias_v)\n elif isinstance(module, Wav2Vec2ConformerPositionalConvEmbedding):\n nn.init.normal_(\n module.conv.weight,\n mean=0,\n std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),\n )\n nn.init.constant_(module.conv.bias, 0)\n elif isinstance(module, Wav2Vec2ConformerFeatureProjection):\n k = math.sqrt(1 / module.projection.in_features)\n nn.init.uniform_(module.projection.weight, a=-k, b=k)\n nn.init.uniform_(module.projection.bias, a=-k, b=k)\n elif isinstance(module, nn.Linear):\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n elif isinstance(module, nn.Conv1d):\n nn.init.kaiming_normal_(module.weight)\n\n if module.bias is not None:\n k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))\n nn.init.uniform_(module.bias, a=-k, b=k)\n\n def _get_feat_extract_output_lengths(\n self, input_lengths: Union[torch.LongTensor, int], add_adapter: Optional[bool] = None\n ):\n \"\"\"\n Computes the output length of the convolutional layers\n \"\"\"\n\n add_adapter = self.config.add_adapter if add_adapter is None else add_adapter\n\n def _conv_out_length(input_length, kernel_size, stride):\n # 1D convolutional layer output length formula taken\n # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html\n return torch_int_div(input_length - kernel_size, stride) + 1\n\n for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):\n input_lengths = _conv_out_length(input_lengths, kernel_size, stride)\n\n if add_adapter:\n for _ in range(self.config.num_adapter_layers):\n input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)\n\n return input_lengths\n\n def _get_feature_vector_attention_mask(\n self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None\n ):\n # Effectively attention_mask.sum(-1), but not inplace to be able to run\n # on inference mode.\n non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]\n\n output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)\n output_lengths = output_lengths.to(torch.long)\n\n batch_size = attention_mask.shape[0]\n\n attention_mask = torch.zeros(\n (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device\n )\n # these two operations makes sure that all values before the output lengths idxs are attended to\n attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1\n attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()\n return attention_mask\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (Wav2Vec2ConformerEncoder, Wav2Vec2ConformerFeatureEncoder)):\n module.gradient_checkpointing = value\n\n\nWAV2VEC2_CONFORMER_START_DOCSTRING = r\"\"\"\n Wav2Vec2Conformer was proposed in [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech\n Representations](https://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael\n Auli.\n\n This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving etc.).\n\n This model is a PyTorch [nn.Module](https://pytorch.org/docs/stable/nn.html#nn.Module) sub-class. Use it as a\n regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.\n\n Parameters:\n config ([`Wav2Vec2ConformerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\n\nWAV2VEC2_CONFORMER_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):\n Float values of input raw speech waveform. Values can be obtained by loading a *.flac* or *.wav* audio file\n into an array of type *List[float]* or a *numpy.ndarray*, *e.g.* via the soundfile library (*pip install\n soundfile*). To prepare the array into *input_values*, the [`Wav2Vec2Processor`] should be used for padding\n and conversion into a tensor of type *torch.FloatTensor*. See [`Wav2Vec2Processor.__call__`] for details.\n attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,\n 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n\n <Tip warning={true}>\n\n `attention_mask` should only be passed if the corresponding processor has `config.return_attention_mask ==\n True`. For all models whose processor has `config.return_attention_mask == False`, such as\n [wav2vec2_conformer-base](https://huggingface.co/facebook/wav2vec2-conformer-large-rel-pos),\n `attention_mask` should **not** be passed to avoid degraded performance when doing batched inference. For\n such models `input_values` should simply be padded with 0 and passed without `attention_mask`. Be aware\n that these models also yield slightly different results depending on whether `input_values` is padded or\n not.\n\n </Tip>\n\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare Wav2Vec2Conformer Model transformer outputting raw hidden-states without any specific head on top.\",\n WAV2VEC2_CONFORMER_START_DOCSTRING,\n)\nclass Wav2Vec2ConformerModel(Wav2Vec2ConformerPreTrainedModel):\n def __init__(self, config: Wav2Vec2ConformerConfig):\n super().__init__(config)\n self.config = config\n self.feature_extractor = Wav2Vec2ConformerFeatureEncoder(config)\n self.feature_projection = Wav2Vec2ConformerFeatureProjection(config)\n\n # model only needs masking vector if mask prob is > 0.0\n if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:\n self.masked_spec_embed = nn.Parameter(torch.FloatTensor(config.hidden_size).uniform_())\n\n self.encoder = Wav2Vec2ConformerEncoder(config)\n\n self.adapter = Wav2Vec2ConformerAdapter(config) if config.add_adapter else None\n\n # Initialize weights and apply final processing\n self.post_init()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model.freeze_feature_encoder\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.feature_extractor._freeze_parameters()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model._mask_hidden_states\n def _mask_hidden_states(\n self,\n hidden_states: torch.FloatTensor,\n mask_time_indices: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n ):\n \"\"\"\n Masks extracted features along time axis and/or along feature axis according to\n [SpecAugment](https://arxiv.org/abs/1904.08779).\n \"\"\"\n\n # `config.apply_spec_augment` can set masking to False\n if not getattr(self.config, \"apply_spec_augment\", True):\n return hidden_states\n\n # generate indices & apply SpecAugment along time axis\n batch_size, sequence_length, hidden_size = hidden_states.size()\n\n if mask_time_indices is not None:\n # apply SpecAugment along time axis with given mask_time_indices\n hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)\n elif self.config.mask_time_prob > 0 and self.training:\n mask_time_indices = _compute_mask_indices(\n (batch_size, sequence_length),\n mask_prob=self.config.mask_time_prob,\n mask_length=self.config.mask_time_length,\n attention_mask=attention_mask,\n min_masks=self.config.mask_time_min_masks,\n )\n mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)\n hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)\n\n if self.config.mask_feature_prob > 0 and self.training:\n # generate indices & apply SpecAugment along feature axis\n mask_feature_indices = _compute_mask_indices(\n (batch_size, hidden_size),\n mask_prob=self.config.mask_feature_prob,\n mask_length=self.config.mask_feature_length,\n min_masks=self.config.mask_feature_min_masks,\n )\n mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)\n mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)\n hidden_states[mask_feature_indices] = 0\n\n return hidden_states\n\n @add_start_docstrings_to_model_forward(WAV2VEC2_CONFORMER_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_PROCESSOR_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Wav2Vec2BaseModelOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_EXPECTED_OUTPUT_SHAPE,\n )\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model.forward with wav2vec2->wav2vec2_conformer\n def forward(\n self,\n input_values: Optional[torch.Tensor],\n attention_mask: Optional[torch.Tensor] = None,\n mask_time_indices: Optional[torch.FloatTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Wav2Vec2BaseModelOutput]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n extract_features = self.feature_extractor(input_values)\n extract_features = extract_features.transpose(1, 2)\n\n if attention_mask is not None:\n # compute reduced attention_mask corresponding to feature vectors\n attention_mask = self._get_feature_vector_attention_mask(\n extract_features.shape[1], attention_mask, add_adapter=False\n )\n\n hidden_states, extract_features = self.feature_projection(extract_features)\n hidden_states = self._mask_hidden_states(\n hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask\n )\n\n encoder_outputs = self.encoder(\n hidden_states,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = encoder_outputs[0]\n\n if self.adapter is not None:\n hidden_states = self.adapter(hidden_states)\n\n if not return_dict:\n return (hidden_states, extract_features) + encoder_outputs[1:]\n\n return Wav2Vec2BaseModelOutput(\n last_hidden_state=hidden_states,\n extract_features=extract_features,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"Wav2Vec2Conformer Model with a quantizer and `VQ` head on top.\"\"\", WAV2VEC2_CONFORMER_START_DOCSTRING\n)\nclass Wav2Vec2ConformerForPreTraining(Wav2Vec2ConformerPreTrainedModel):\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTraining.__init__ with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer\n def __init__(self, config: Wav2Vec2ConformerConfig):\n super().__init__(config)\n self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)\n self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)\n\n self.quantizer = Wav2Vec2ConformerGumbelVectorQuantizer(config)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n # make sure that project_hid & project_q are initialized like normal linear layers\n self.project_hid = nn.Linear(config.hidden_size, config.proj_codevector_dim)\n self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTraining.set_gumbel_temperature\n def set_gumbel_temperature(self, temperature: int):\n \"\"\"\n Set the Gumbel softmax temperature to a given value. Only necessary for training\n \"\"\"\n self.quantizer.temperature = temperature\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTraining.freeze_feature_encoder with wav2vec2->wav2vec2_conformer\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wav2vec2_conformer.feature_extractor._freeze_parameters()\n\n @staticmethod\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTraining.compute_contrastive_logits\n def compute_contrastive_logits(\n target_features: torch.FloatTensor,\n negative_features: torch.FloatTensor,\n predicted_features: torch.FloatTensor,\n temperature: int = 0.1,\n ):\n \"\"\"\n Compute logits for contrastive loss based using cosine similarity as the distance measure between\n `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.\n \"\"\"\n target_features = torch.cat([target_features, negative_features], dim=0)\n\n logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1).type_as(\n target_features\n )\n\n # apply temperature\n logits = logits / temperature\n return logits\n\n @add_start_docstrings_to_model_forward(WAV2VEC2_CONFORMER_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Wav2Vec2ConformerForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForPreTraining.forward with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer,wav2vec2_conformer-base->wav2vec2-conformer-rel-pos-large\n def forward(\n self,\n input_values: Optional[torch.Tensor],\n attention_mask: Optional[torch.Tensor] = None,\n mask_time_indices: Optional[torch.BoolTensor] = None,\n sampled_negative_indices: Optional[torch.BoolTensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, Wav2Vec2ConformerForPreTrainingOutput]:\n r\"\"\"\n mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict\n masked extracted features in *config.proj_codevector_dim* space.\n sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):\n Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.\n Required input for pre-training.\n\n Returns:\n\n Example:\n\n ```python\n >>> import torch\n >>> from transformers import AutoFeatureExtractor, Wav2Vec2ConformerForPreTraining\n >>> from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer import _compute_mask_indices\n >>> from datasets import load_dataset\n\n >>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"facebook/wav2vec2-conformer-rel-pos-large\")\n >>> model = Wav2Vec2ConformerForPreTraining.from_pretrained(\"facebook/wav2vec2-conformer-rel-pos-large\")\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> input_values = feature_extractor(ds[0][\"audio\"][\"array\"], return_tensors=\"pt\").input_values # Batch size 1\n\n >>> # compute masked indices\n >>> batch_size, raw_sequence_length = input_values.shape\n >>> sequence_length = model._get_feat_extract_output_lengths(raw_sequence_length)\n >>> mask_time_indices = _compute_mask_indices((batch_size, sequence_length), mask_prob=0.2, mask_length=2)\n >>> mask_time_indices = torch.tensor(mask_time_indices, device=input_values.device, dtype=torch.long)\n\n >>> with torch.no_grad():\n ... outputs = model(input_values, mask_time_indices=mask_time_indices)\n\n >>> # compute cosine similarity between predicted (=projected_states) and target (=projected_quantized_states)\n >>> cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)\n\n >>> # show that cosine similarity is much higher than random\n >>> cosine_sim[mask_time_indices.to(torch.bool)].mean() > 0.5\n tensor(True)\n\n >>> # for contrastive loss training model should be put into train mode\n >>> model = model.train()\n >>> loss = model(input_values, mask_time_indices=mask_time_indices).loss\n ```\"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if mask_time_indices is not None:\n mask_time_indices = mask_time_indices.to(torch.bool)\n\n outputs = self.wav2vec2_conformer(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n mask_time_indices=mask_time_indices,\n return_dict=return_dict,\n )\n\n # 1. project all transformed features (including masked) to final vq dim\n transformer_features = self.project_hid(outputs[0])\n\n # 2. quantize all (unmasked) extracted features and project to final vq dim\n extract_features = self.dropout_features(outputs[1])\n\n if attention_mask is not None:\n # compute reduced attention_mask correponding to feature vectors\n attention_mask = self._get_feature_vector_attention_mask(\n extract_features.shape[1], attention_mask, add_adapter=False\n )\n\n quantized_features, codevector_perplexity = self.quantizer(\n extract_features, mask_time_indices=mask_time_indices\n )\n quantized_features = self.project_q(quantized_features)\n\n loss = contrastive_loss = diversity_loss = None\n if sampled_negative_indices is not None:\n batch_size, sequence_length, hidden_size = quantized_features.shape\n\n # for training, we sample negatives\n # 3. sample K negatives (distractors) quantized states for contrastive loss\n # if attention_mask is passed, make sure that padded feature vectors cannot be sampled\n # sample negative quantized vectors BTC => (BxT)C\n negative_quantized_features = quantized_features.view(-1, hidden_size)[\n sampled_negative_indices.long().view(-1)\n ]\n negative_quantized_features = negative_quantized_features.view(\n batch_size, sequence_length, -1, hidden_size\n ).permute(2, 0, 1, 3)\n\n # 4. compute logits, corresponding to `logs = sim(c_t, [q_t, \\sim{q}_t]) / \\kappa`\n # of equation (3) in https://arxiv.org/pdf/2006.11477.pdf\n logits = self.compute_contrastive_logits(\n quantized_features[None, :],\n negative_quantized_features,\n transformer_features,\n self.config.contrastive_logits_temperature,\n )\n\n # 5. if a negative vector is identical to the positive (i.e. when codebook utilization is low),\n # its cosine similarity will be masked\n neg_is_pos = (quantized_features == negative_quantized_features).all(-1)\n\n if neg_is_pos.any():\n logits[1:][neg_is_pos] = float(\"-inf\")\n\n # 6. compute contrastive loss \\mathbf{L}_m = cross_entropy(logs) =\n # -log(exp(sim(c_t, q_t)/\\kappa) / \\sum_{\\sim{q}} exp(sim(c_t, \\sim{q})/\\kappa))\n logits = logits.transpose(0, 2).reshape(-1, logits.size(0))\n target = ((1 - mask_time_indices.long()) * -100).transpose(0, 1).flatten()\n\n contrastive_loss = nn.functional.cross_entropy(logits.float(), target, reduction=\"sum\")\n # 7. compute diversity loss: \\mathbf{L}_d\n num_codevectors = self.config.num_codevectors_per_group * self.config.num_codevector_groups\n diversity_loss = ((num_codevectors - codevector_perplexity) / num_codevectors) * mask_time_indices.sum()\n\n # 8. \\mathbf{L} = \\mathbf{L}_m + \\alpha * \\mathbf{L}_d\n loss = contrastive_loss + self.config.diversity_loss_weight * diversity_loss\n\n if not return_dict:\n if loss is not None:\n return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]\n return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]\n\n return Wav2Vec2ConformerForPreTrainingOutput(\n loss=loss,\n projected_states=transformer_features,\n projected_quantized_states=quantized_features,\n codevector_perplexity=codevector_perplexity,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n contrastive_loss=contrastive_loss,\n diversity_loss=diversity_loss,\n )\n\n\n@add_start_docstrings(\n \"\"\"Wav2Vec2Conformer Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\"\"\",\n WAV2VEC2_CONFORMER_START_DOCSTRING,\n)\nclass Wav2Vec2ConformerForCTC(Wav2Vec2ConformerPreTrainedModel):\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.__init__ with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer\n def __init__(self, config):\n super().__init__(config)\n\n self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)\n self.dropout = nn.Dropout(config.final_dropout)\n\n if config.vocab_size is None:\n raise ValueError(\n f\"You are trying to instantiate {self.__class__} with a configuration that does not define the\"\n \" vocabulary size of the language model head. Please instantiate the model as follows:\"\n \" `Wav2Vec2ConformerForCTC.from_pretrained(..., vocab_size=vocab_size)`. or define `vocab_size` of\"\n \" your model's configuration.\"\n )\n output_hidden_size = (\n config.output_hidden_size if hasattr(config, \"add_adapter\") and config.add_adapter else config.hidden_size\n )\n self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.freeze_feature_encoder with wav2vec2->wav2vec2_conformer\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wav2vec2_conformer.feature_extractor._freeze_parameters()\n\n @add_start_docstrings_to_model_forward(WAV2VEC2_CONFORMER_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_PROCESSOR_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=CausalLMOutput,\n config_class=_CONFIG_FOR_DOC,\n expected_output=_CTC_EXPECTED_OUTPUT,\n expected_loss=_CTC_EXPECTED_LOSS,\n )\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.forward with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer\n def forward(\n self,\n input_values: Optional[torch.Tensor],\n attention_mask: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: Optional[torch.Tensor] = None,\n ) -> Union[Tuple, CausalLMOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):\n Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to\n the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.\n All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,\n config.vocab_size - 1]`.\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.wav2vec2_conformer(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n hidden_states = self.dropout(hidden_states)\n\n logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n\n if labels.max() >= self.config.vocab_size:\n raise ValueError(f\"Label values must be <= vocab_size: {self.config.vocab_size}\")\n\n # retrieve loss input_lengths from attention_mask\n attention_mask = (\n attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)\n )\n input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)\n\n # assuming that padded tokens are filled with -100\n # when not being attended to\n labels_mask = labels >= 0\n target_lengths = labels_mask.sum(-1)\n flattened_targets = labels.masked_select(labels_mask)\n\n # ctc_loss doesn't support fp16\n log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)\n\n with torch.backends.cudnn.flags(enabled=False):\n loss = nn.functional.ctc_loss(\n log_probs,\n flattened_targets,\n input_lengths,\n target_lengths,\n blank=self.config.pad_token_id,\n reduction=self.config.ctc_loss_reduction,\n zero_infinity=self.config.ctc_zero_infinity,\n )\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return CausalLMOutput(\n loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions\n )\n\n\n@add_start_docstrings(\n \"\"\"\n Wav2Vec2Conformer Model with a sequence classification head on top (a linear layer over the pooled output) for\n tasks like SUPERB Keyword Spotting.\n \"\"\",\n WAV2VEC2_CONFORMER_START_DOCSTRING,\n)\nclass Wav2Vec2ConformerForSequenceClassification(Wav2Vec2ConformerPreTrainedModel):\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.__init__ with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer\n def __init__(self, config):\n super().__init__(config)\n\n if hasattr(config, \"add_adapter\") and config.add_adapter:\n raise ValueError(\n \"Sequence classification does not support the use of Wav2Vec2Conformer adapters\"\n \" (config.add_adapter=True)\"\n )\n self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)\n num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings\n if config.use_weighted_layer_sum:\n self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)\n self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)\n self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.freeze_feature_encoder with wav2vec2->wav2vec2_conformer\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wav2vec2_conformer.feature_extractor._freeze_parameters()\n\n def freeze_base_model(self):\n \"\"\"\n Calling this function will disable the gradient computation for the base model so that its parameters will not\n be updated during training. Only the classification head will be updated.\n \"\"\"\n for param in self.wav2vec2_conformer.parameters():\n param.requires_grad = False\n\n @add_start_docstrings_to_model_forward(WAV2VEC2_CONFORMER_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_FEAT_EXTRACTOR_FOR_DOC,\n checkpoint=_SEQ_CLASS_CHECKPOINT,\n output_type=SequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,\n expected_loss=_SEQ_CLASS_EXPECTED_LOSS,\n )\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.forward with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer,WAV_2_VEC_2->WAV2VEC2_CONFORMER\n def forward(\n self,\n input_values: Optional[torch.Tensor],\n attention_mask: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: Optional[torch.Tensor] = None,\n ) -> Union[Tuple, SequenceClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states\n\n outputs = self.wav2vec2_conformer(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if self.config.use_weighted_layer_sum:\n hidden_states = outputs[_HIDDEN_STATES_START_POSITION]\n hidden_states = torch.stack(hidden_states, dim=1)\n norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)\n hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)\n else:\n hidden_states = outputs[0]\n\n hidden_states = self.projector(hidden_states)\n if attention_mask is None:\n pooled_output = hidden_states.mean(dim=1)\n else:\n padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)\n hidden_states[~padding_mask] = 0.0\n pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)\n\n logits = self.classifier(pooled_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return SequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n Wav2Vec2Conformer Model with a frame classification head on top for tasks like Speaker Diarization.\n \"\"\",\n WAV2VEC2_CONFORMER_START_DOCSTRING,\n)\nclass Wav2Vec2ConformerForAudioFrameClassification(Wav2Vec2ConformerPreTrainedModel):\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForAudioFrameClassification.__init__ with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer,WAV_2_VEC_2->WAV2VEC2_CONFORMER\n def __init__(self, config):\n super().__init__(config)\n\n if hasattr(config, \"add_adapter\") and config.add_adapter:\n raise ValueError(\n \"Audio frame classification does not support the use of Wav2Vec2Conformer adapters\"\n \" (config.add_adapter=True)\"\n )\n self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)\n num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings\n if config.use_weighted_layer_sum:\n self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n self.num_labels = config.num_labels\n\n self.init_weights()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForAudioFrameClassification.freeze_feature_encoder with wav2vec2->wav2vec2_conformer\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wav2vec2_conformer.feature_extractor._freeze_parameters()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForAudioFrameClassification.freeze_base_model with wav2vec2->wav2vec2_conformer\n def freeze_base_model(self):\n \"\"\"\n Calling this function will disable the gradient computation for the base model so that its parameters will not\n be updated during training. Only the classification head will be updated.\n \"\"\"\n for param in self.wav2vec2_conformer.parameters():\n param.requires_grad = False\n\n @add_start_docstrings_to_model_forward(WAV2VEC2_CONFORMER_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_FEAT_EXTRACTOR_FOR_DOC,\n checkpoint=_FRAME_CLASS_CHECKPOINT,\n output_type=TokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_FRAME_EXPECTED_OUTPUT,\n )\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForAudioFrameClassification.forward with wav2vec2->wav2vec2_conformer\n def forward(\n self,\n input_values: Optional[torch.Tensor],\n attention_mask: Optional[torch.Tensor] = None,\n labels: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, TokenClassifierOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states\n\n outputs = self.wav2vec2_conformer(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if self.config.use_weighted_layer_sum:\n hidden_states = outputs[_HIDDEN_STATES_START_POSITION]\n hidden_states = torch.stack(hidden_states, dim=1)\n norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)\n hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)\n else:\n hidden_states = outputs[0]\n\n logits = self.classifier(hidden_states)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return output\n\n return TokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.AMSoftmaxLoss\nclass AMSoftmaxLoss(nn.Module):\n def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):\n super(AMSoftmaxLoss, self).__init__()\n self.scale = scale\n self.margin = margin\n self.num_labels = num_labels\n self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)\n self.loss = nn.CrossEntropyLoss()\n\n def forward(self, hidden_states, labels):\n labels = labels.flatten()\n weight = nn.functional.normalize(self.weight, dim=0)\n hidden_states = nn.functional.normalize(hidden_states, dim=1)\n cos_theta = torch.mm(hidden_states, weight)\n psi = cos_theta - self.margin\n\n onehot = nn.functional.one_hot(labels, self.num_labels)\n logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)\n loss = self.loss(logits, labels)\n\n return loss\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.TDNNLayer\nclass TDNNLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]\n self.out_conv_dim = config.tdnn_dim[layer_id]\n self.kernel_size = config.tdnn_kernel[layer_id]\n self.dilation = config.tdnn_dilation[layer_id]\n\n self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)\n self.activation = nn.ReLU()\n\n def forward(self, hidden_states):\n hidden_states = hidden_states.unsqueeze(1)\n hidden_states = nn.functional.unfold(\n hidden_states,\n (self.kernel_size, self.in_conv_dim),\n stride=(1, self.in_conv_dim),\n dilation=(self.dilation, 1),\n )\n hidden_states = hidden_states.transpose(1, 2)\n hidden_states = self.kernel(hidden_states)\n\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n@add_start_docstrings(\n \"\"\"\n Wav2Vec2Conformer Model with an XVector feature extraction head on top for tasks like Speaker Verification.\n \"\"\",\n WAV2VEC2_CONFORMER_START_DOCSTRING,\n)\nclass Wav2Vec2ConformerForXVector(Wav2Vec2ConformerPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)\n num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings\n if config.use_weighted_layer_sum:\n self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)\n self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])\n\n tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]\n self.tdnn = nn.ModuleList(tdnn_layers)\n\n self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)\n self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)\n\n self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)\n\n self.init_weights()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForXVector.freeze_feature_encoder with wav2vec2->wav2vec2_conformer\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wav2vec2_conformer.feature_extractor._freeze_parameters()\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForXVector.freeze_base_model with wav2vec2->wav2vec2_conformer\n def freeze_base_model(self):\n \"\"\"\n Calling this function will disable the gradient computation for the base model so that its parameters will not\n be updated during training. Only the classification head will be updated.\n \"\"\"\n for param in self.wav2vec2_conformer.parameters():\n param.requires_grad = False\n\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForXVector._get_tdnn_output_lengths with wav2vec2->wav2vec2_conformer\n def _get_tdnn_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):\n \"\"\"\n Computes the output length of the TDNN layers\n \"\"\"\n\n def _conv_out_length(input_length, kernel_size, stride):\n # 1D convolutional layer output length formula taken\n # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html\n return (input_length - kernel_size) // stride + 1\n\n for kernel_size in self.config.tdnn_kernel:\n input_lengths = _conv_out_length(input_lengths, kernel_size, 1)\n\n return input_lengths\n\n @add_start_docstrings_to_model_forward(WAV2VEC2_CONFORMER_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_FEAT_EXTRACTOR_FOR_DOC,\n checkpoint=_XVECTOR_CHECKPOINT,\n output_type=XVectorOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_XVECTOR_EXPECTED_OUTPUT,\n )\n # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForXVector.forward with Wav2Vec2->Wav2Vec2Conformer,wav2vec2->wav2vec2_conformer,WAV_2_VEC_2->WAV2VEC2_CONFORMER\n def forward(\n self,\n input_values: Optional[torch.Tensor],\n attention_mask: Optional[torch.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n labels: Optional[torch.Tensor] = None,\n ) -> Union[Tuple, XVectorOutput]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states\n\n outputs = self.wav2vec2_conformer(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if self.config.use_weighted_layer_sum:\n hidden_states = outputs[_HIDDEN_STATES_START_POSITION]\n hidden_states = torch.stack(hidden_states, dim=1)\n norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)\n hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)\n else:\n hidden_states = outputs[0]\n\n hidden_states = self.projector(hidden_states)\n\n for tdnn_layer in self.tdnn:\n hidden_states = tdnn_layer(hidden_states)\n\n # Statistic Pooling\n if attention_mask is None:\n mean_features = hidden_states.mean(dim=1)\n std_features = hidden_states.std(dim=1)\n else:\n feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))\n tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)\n mean_features = []\n std_features = []\n for i, length in enumerate(tdnn_output_lengths):\n mean_features.append(hidden_states[i, :length].mean(dim=0))\n std_features.append(hidden_states[i, :length].std(dim=0))\n mean_features = torch.stack(mean_features)\n std_features = torch.stack(std_features)\n statistic_pooling = torch.cat([mean_features, std_features], dim=-1)\n\n output_embeddings = self.feature_extractor(statistic_pooling)\n logits = self.classifier(output_embeddings)\n\n loss = None\n if labels is not None:\n loss = self.objective(logits, labels)\n\n if not return_dict:\n output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return XVectorOutput(\n loss=loss,\n logits=logits,\n embeddings=output_embeddings,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n" ]
[ [ "pandas.DataFrame.from_records", "numpy.array", "torch.no_grad", "pandas.DataFrame.from_dict" ], [ "torch.Size", "torch.ones", "torch.cat", "torch.zeros", "torch.manual_seed", "torch.einsum", "torch.tensor", "torch.no_grad", "torch.allclose", "torch.ones_like", "torch.argmax" ], [ "torch.nn.functional.softmax", "torch.nn.functional.dropout", "torch.zeros", "torch.cat", "torch.masked_fill", "torch.nn.Embedding", "torch.tanh", "torch.nn.BCEWithLogitsLoss", "torch.finfo", "torch.nn.Dropout", "torch.nn.CrossEntropyLoss", "torch.ones", "torch.einsum", "torch.bmm", "torch.arange", "torch.nn.functional.pad", "torch.zeros_like", "torch.nn.Linear", "torch.nn.LayerNorm", "torch.nn.Tanh", "torch.cumsum", "torch.nn.MSELoss" ], [ "torch.nn.functional.dropout", "torch.cat", "torch.nn.Embedding", "torch.nn.BCEWithLogitsLoss", "torch.finfo", "torch.full_like", "torch.nn.Dropout", "torch.nn.CrossEntropyLoss", "numpy.sin", "torch.tensor", "torch.arange", "torch.nn.AdaptiveLogSoftmaxWithLoss", "torch.full", "numpy.power", "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.nn.Linear", "torch.nn.init.normal_", "numpy.cos", "torch.nn.LayerNorm", "torch.matmul", "torch.nn.MSELoss" ], [ "torch.Size", "numpy.random.seed", "torch.zeros", "torch.tensor", "torch.no_grad", "torch.rand", "numpy.random.rand", "torch.allclose", "torch.as_tensor" ], [ "torch.nn.GLU", "torch.nn.init.uniform_", "torch.nn.functional.softmax", "torch.nn.functional.glu", "torch.cat", "torch.sin", "torch.zeros", "torch.FloatTensor", "torch.finfo", "numpy.random.randint", "torch.nn.Dropout", "torch.softmax", "torch.nn.CrossEntropyLoss", "torch.mm", "torch.ones", "numpy.arange", "torch.einsum", "torch.randn", "torch.backends.cudnn.flags", "torch.tensor", "torch.arange", "torch.nn.GroupNorm", "numpy.zeros", "torch.ones_like", "torch.cos", "torch.nn.BatchNorm1d", "torch.nn.init.constant_", "numpy.put_along_axis", "torch.nn.ModuleList", "torch.zeros_like", "torch.nn.Linear", "torch.log", "numpy.random.rand", "torch.nn.Conv1d", "torch.stack", "torch.flip", "numpy.array", "torch.nn.functional.ctc_loss", "torch.nn.functional.normalize", "numpy.random.random", "torch.Tensor", "torch.nn.functional.log_softmax", "torch.nn.utils.weight_norm", "numpy.ones", "torch.nn.LayerNorm", "torch.matmul", "numpy.random.uniform", "numpy.broadcast_to", "torch.nn.init.xavier_uniform_", "torch.nn.functional.one_hot", "torch.nn.functional.unfold", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_" ] ]
[ { "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": [], "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": [] } ]
Haiper-ai/kubric
[ "d096ba178b8a78ea2c840ae121646d36281d31d9" ]
[ "challenges/multiview_matting/worker.py" ]
[ "# Copyright 2021 The Kubric 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nWorker file for the Multi-View Background removal dataset.\n\nThis dataset creates a scene where a foreground object is to be distinguished\nfrom the background. Foreground objects are borrowed from shapnet. Backgrounds\nare from indoor scenes of polyhaven. All foreground objects are situated on top\nof a \"table\" which is gernated to be random in color. Instead of background\nremoval with a single image. This dataset is special in that multiple images of\nthe foreground object (taken from different camera poses) are given. This\n\"multi-view\" persepctive should be very helpful for background removal but is\ncurrently underexplored in the literature.\n\"\"\"\nimport logging\nimport numpy as np\n\nimport kubric as kb\nfrom kubric.renderer import Blender as KubricRenderer\n\n# --- WARNING: this path is not yet public\nsource_path = (\n \"gs://tensorflow-graphics/public/60c9de9c410be30098c297ac/ShapeNetCore.v2\")\n\n# --- CLI arguments (and modified defaults)\nparser = kb.ArgumentParser()\nparser.set_defaults(\n seed=1,\n frame_start=1,\n frame_end=10,\n width=128,\n height=128,\n)\n\nparser.add_argument(\"--backgrounds_split\",\n choices=[\"train\", \"test\"], default=\"train\")\nparser.add_argument(\"--dataset_mode\",\n choices=[\"easy\", \"hard\"], default=\"hard\")\nparser.add_argument(\"--hdri_dir\",\n type=str, default=\"gs://mv_bckgr_removal/hdri_haven/4k/\")\n # \"/mnt/mydata/images/\"\nFLAGS = parser.parse_args()\n\n\nif FLAGS.dataset_mode == \"hard\":\n add_distractors = False\n\ndef add_hdri_dome(hdri_source, scene, background_hdri=None):\n dome_path = hdri_source.fetch(\"dome.blend\")\n dome = kb.FileBasedObject(\n name=\"BackgroundDome\",\n position=(0, 0, 0),\n static=True, background=True,\n simulation_filename=None,\n render_filename=str(dome_path),\n render_import_kwargs={\n \"filepath\": str(dome_path / \"Object\" / \"Dome\"),\n \"directory\": str(dome_path / \"Object\"),\n \"filename\": \"Dome\",\n })\n scene.add(dome)\n # pylint: disable=import-outside-toplevel\n from kubric.renderer import Blender\n import bpy\n blender_renderer = [v for v in scene.views if isinstance(v, Blender)]\n if blender_renderer:\n dome_blender = dome.linked_objects[blender_renderer[0]]\n dome_blender.cycles_visibility.shadow = False\n if background_hdri is not None:\n dome_mat = dome_blender.data.materials[0]\n texture_node = dome_mat.node_tree.nodes[\"Image Texture\"]\n texture_node.image = bpy.data.images.load(background_hdri.filename)\n return dome\n\n# --- Common setups\nkb.utils.setup_logging(FLAGS.logging_level)\nkb.utils.log_my_flags(FLAGS)\njob_dir = kb.as_path(FLAGS.job_dir)\nrng = np.random.RandomState(FLAGS.seed)\nscene = kb.Scene.from_flags(FLAGS)\n\n# --- Add a renderer\nrenderer = KubricRenderer(scene,\n use_denoising=True,\n adaptive_sampling=False,\n background_transparency=True)\n\n# --- Fetch a random asset\nasset_source = kb.AssetSource(source_path)\nall_ids = list(asset_source.db['id'])\nfraction = 0.1\nheld_out_obj_ids = list(asset_source.db.sample(\n frac=fraction, replace=False, random_state=42)[\"id\"])\ntrain_obj_ids = [i for i in asset_source.db[\"id\"] if\n i not in held_out_obj_ids]\n\nif FLAGS.backgrounds_split == \"train\":\n asset_id = rng.choice(train_obj_ids)\nelse:\n asset_id = rng.choice(held_out_obj_ids)\n\nobj = asset_source.create(asset_id=asset_id)\nlogging.info(f\"selected '{asset_id}'\")\n\n# --- make object flat on X/Y and not penetrate floor\nobj.quaternion = kb.Quaternion(axis=[1,0,0], degrees=90)\nobj.position = obj.position - (0, 0, obj.aabbox[0][2])\n\nobj_size = np.linalg.norm(obj.aabbox[1] - obj.aabbox[0])\nif add_distractors:\n obj_radius = np.linalg.norm(obj.aabbox[1][:2] - obj.aabbox[0][:2])\nobj_height = obj.aabbox[1][2] - obj.aabbox[0][2]\nobj.metadata = {\n \"asset_id\": obj.asset_id,\n \"category\": asset_source.db[\n asset_source.db[\"id\"] == obj.asset_id].iloc[0][\"category_name\"],\n}\nscene.add(obj)\n\nsize_multiple = 1.\nif add_distractors:\n distractor_locs = []\n for i in range(4):\n asset_id_2 = rng.choice(train_obj_ids)\n obj2 = asset_source.create(asset_id=asset_id_2)\n logging.info(f\"selected '{asset_id}'\")\n\n # --- make object flat on X/Y and not penetrate floor\n obj2.quaternion = kb.Quaternion(axis=[1,0,0], degrees=90)\n obj_2_radius = np.linalg.norm(obj2.aabbox[1][:2] - obj2.aabbox[0][:2])\n\n position = rng.rand((2)) * 2 - 1\n position /= np.linalg.norm(position)\n position *= (obj_radius + obj_2_radius) / 2.\n\n distractor_locs.append(-position)\n obj2.position = obj2.position - (position[0], position[1], obj2.aabbox[0][2])\n\n obj_size_2 = np.linalg.norm(obj2.aabbox[1] - obj2.aabbox[0])\n\n obj_height_2 = obj2.aabbox[1][2] - obj2.aabbox[0][2]\n obj2.metadata = {\n \"asset_id\": obj.asset_id,\n \"category\": asset_source.db[\n asset_source.db[\"id\"] == obj2.asset_id].iloc[0][\"category_name\"],\n }\n scene.add(obj2)\n\n distractor_dir = np.vstack(distractor_locs)\n distractor_dir /= np.linalg.norm(distractor_dir, axis=-1, keepdims=True)\n\n size_multiple = 1.5\n\nmaterial = kb.PrincipledBSDFMaterial(\n color=kb.Color.from_hsv(rng.uniform(), 1, 1),\n metallic=1.0, roughness=0.2, ior=2.5)\n\ntable = kb.Cube(name=\"floor\", scale=(obj_size*size_multiple, obj_size*size_multiple, 0.02),\n position=(0, 0, -0.02), material=material)\nscene += table\n\nlogging.info(\"Loading background HDRIs from %s\", FLAGS.hdri_dir)\n\nhdri_source = kb.TextureSource(FLAGS.hdri_dir)\ntrain_backgrounds, held_out_backgrounds = hdri_source.get_test_split(\n fraction=0.1)\nif FLAGS.backgrounds_split == \"train\":\n logging.info(\"Choosing one of the %d training backgrounds...\",\n len(train_backgrounds))\n background_hdri = hdri_source.create(texture_name=rng.choice(train_backgrounds))\nelse:\n logging.info(\"Choosing one of the %d held-out backgrounds...\",\n len(held_out_backgrounds))\n background_hdri = hdri_source.create(\n texture_name=rng.choice(held_out_backgrounds))\ndome = kb.assets.utils.add_hdri_dome(hdri_source, scene, background_hdri)\n\ndome = add_hdri_dome(hdri_source, scene, background_hdri)\nrenderer._set_ambient_light_hdri(background_hdri.filename)\n# table = add_table(hdri_source, scene, background_hdri)\n\n# --- Add Klevr-like lights to the scene\nscene += kb.assets.utils.get_clevr_lights(rng=rng)\n# scene.ambient_illumination = kb.Color.from_hsv(np.random.uniform(), 1, 1)\n# scene.ambient_illumination = kb.Color(0.05, 0.05, 0.05)\n\ndef sample_point_in_half_sphere_shell(\n inner_radius: float,\n outer_radius: float,\n rng: np.random.RandomState\n ):\n \"\"\"Uniformly sample points that are in a given distance\n range from the origin and with z >= 0.\"\"\"\n\n while True:\n v = rng.uniform((-outer_radius, -outer_radius, obj_height/1.2),\n (outer_radius, outer_radius, obj_height))\n len_v = np.linalg.norm(v)\n correct_angle = True\n if add_distractors:\n cam_dir = v[:2] / np.linalg.norm(v[:2])\n correct_angle = np.all(np.dot(distractor_dir, cam_dir) < np.cos(np.pi / 9.))\n if inner_radius <= len_v <= outer_radius and correct_angle:\n return tuple(v)\n\n# --- Keyframe the camera\nscene.camera = kb.PerspectiveCamera()\nfor frame in range(FLAGS.frame_start, FLAGS.frame_end + 1):\n # scene.camera.position = (1, 1, 1) #< frozen camera\n scene.camera.position = sample_point_in_half_sphere_shell(\n obj_size*1.7, obj_size*2, rng)\n scene.camera.look_at((0, 0, obj_height/2))\n scene.camera.keyframe_insert(\"position\", frame)\n scene.camera.keyframe_insert(\"quaternion\", frame)\n\n# --- Rendering\nlogging.info(\"Rendering the scene ...\")\nrenderer.save_state(job_dir / \"scene.blend\")\ndata_stack = renderer.render()\n\n# --- Postprocessing\nkb.compute_visibility(data_stack[\"segmentation\"], scene.assets)\ndata_stack[\"segmentation\"] = kb.adjust_segmentation_idxs(\n data_stack[\"segmentation\"],\n scene.assets,\n [obj]).astype(np.uint8)\n\n# --- Discard non-used information\ndel data_stack[\"uv\"]\ndel data_stack[\"forward_flow\"]\ndel data_stack[\"backward_flow\"]\ndel data_stack[\"depth\"]\ndel data_stack[\"normal\"]\n\n# --- Save to image files\nkb.file_io.write_image_dict(data_stack, job_dir)\n\n# --- Collect metadata\nlogging.info(\"Collecting and storing metadata for each object.\")\ndata = {\n \"metadata\": kb.get_scene_metadata(scene),\n \"camera\": kb.get_camera_info(scene.camera),\n}\nkb.file_io.write_json(filename=job_dir / \"metadata.json\", data=data)\nkb.done()\n" ]
[ [ "numpy.dot", "numpy.cos", "numpy.linalg.norm", "numpy.random.RandomState", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KiLJ4EdeN/tf2_nn
[ "0ccec7692f061e7e066a4a2439683e3b09faa7bc" ]
[ "tfnn_mlp.py" ]
[ "import tensorflow as tf\nimport matplotlib.pyplot as plt\n\n# MNIST dataset parameters.\nnum_classes = 10 # 0 to 9 digits\nnum_features = 784 # 28*28\n\n# Training parameters.\nlearning_rate = 0.001\ntraining_steps = 1000\nbatch_size = 256\ndisplay_step = 100\n\n# Network parameters.\nn_hidden_1 = 128 # 1st layer number of neurons.\nn_hidden_2 = 256 # 2nd layer number of neurons.\n\n# Prepare MNIST data.\nfrom tensorflow.keras.datasets import mnist\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\n# Convert to float32.\nX_train = tf.Variable(X_train, dtype=tf.float32)\nX_test = tf.Variable(X_test, dtype=tf.float32)\n# Flatten images to 1-D vector of 784 features (28*28).\nX_train = tf.reshape(X_train, [-1, num_features])\nX_test = tf.reshape(X_test, [-1, num_features])\n# Normalize images value from [0, 255] to [0, 1].\nX_train = X_train / 255.\nX_test = X_test / 255.\n\nprint(X_train.shape)\nprint(X_test.shape)\n\n# Use tf.data API to shuffle and batch data.\ntrain_data = tf.data.Dataset.from_tensor_slices((X_train, Y_train))\n# repeat adds the data again, prefetch speeds up outputs with the cost of ram.\ntrain_data = train_data.repeat().shuffle(5000).batch(batch_size).prefetch(1)\n\nnum_hidden_units = [n_hidden_1, n_hidden_2, num_classes]\nrandom_normal = tf.initializers.RandomNormal()\n# Weight of shape [784, 10], the 28*28 image features, and total number of classes.\nW1 = tf.Variable(random_normal([num_features, num_hidden_units[0]]), name=\"weight1\")\nW2 = tf.Variable(random_normal([num_hidden_units[0], num_hidden_units[1]]), name=\"weight2\")\nW3 = tf.Variable(random_normal([num_hidden_units[1], num_hidden_units[2]]), name=\"weight3\")\n# Bias of shape [10], the total number of classes.\nb1 = tf.Variable(tf.zeros([num_hidden_units[0]]), name=\"bias1\")\nb2 = tf.Variable(tf.zeros([num_hidden_units[1]]), name=\"bias2\")\nb3 = tf.Variable(tf.zeros([num_hidden_units[2]]), name=\"bias3\")\n\ndef multilayer_perceptron(x):\n # Apply softmax to normalize the logits to a probability distribution.\n h1 = tf.nn.relu(tf.add(tf.matmul(x, W1), b1))\n h2 = tf.nn.relu(tf.add(tf.matmul(h1, W2), b2))\n h3 = tf.nn.relu(tf.add(tf.matmul(h2, W3), b3))\n return tf.nn.softmax(h3)\n\n# Cross-Entropy loss function.\ndef cross_entropy(y_pred, y_true):\n # Encode label to a one hot vector.\n y_true = tf.one_hot(y_true, depth=num_classes)\n # Clip prediction values to avoid log(0) error.\n y_pred = tf.clip_by_value(y_pred, 1e-9, 1.)\n # Compute cross-entropy.\n return tf.reduce_mean(-tf.reduce_sum(y_true * tf.math.log(y_pred)))\n\n# Accuracy metric.\ndef accuracy(y_pred, y_true):\n # Predicted class is the index of highest score in prediction vector (i.e. argmax).\n correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64))\n return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1)\n\n# Stochastic gradient descent optimizer.\noptimizer = tf.optimizers.SGD(learning_rate)\n\n# Optimization process. \ndef run_optimization(x, y):\n # Wrap computation inside a GradientTape for automatic differentiation.\n with tf.GradientTape() as g:\n pred = multilayer_perceptron(x)\n loss = cross_entropy(pred, y)\n\n # Compute gradients.\n gradients = g.gradient(loss, [W1, W2, W3, b1, b2, b3])\n \n # Update W and b following gradients.\n optimizer.apply_gradients(zip(gradients, [W1, W2, W3, b1, b2, b3]))\n\n# Run training for the given number of steps.\nfor step, (batch_x, batch_y) in enumerate(train_data.take(training_steps), 1):\n # Run the optimization to update W and b values.\n run_optimization(batch_x, batch_y)\n \n if step % display_step == 0:\n pred = multilayer_perceptron(batch_x)\n loss = cross_entropy(pred, batch_y)\n acc = accuracy(pred, batch_y)\n print(\"step: %i, loss: %f, accuracy: %f\" % (step, loss, acc))\n\n# Test model on validation set.\npred = multilayer_perceptron(X_test)\nprint(\"Test Accuracy: %f\" % accuracy(pred, Y_test))\n\n# Visualize predictions.\n# Predict 5 images from validation set.\nn_images = 5\ntest_images = X_test[:n_images]\npredictions = multilayer_perceptron(test_images)\n\n# Display image and model prediction.\nfor i in range(n_images):\n plt.imshow(tf.reshape(test_images[i], [28, 28]), cmap='gray')\n plt.show()\n print(\"Model prediction: %i\" % tf.argmax(predictions.numpy()[i]))\n" ]
[ [ "tensorflow.clip_by_value", "tensorflow.matmul", "tensorflow.nn.softmax", "tensorflow.Variable", "tensorflow.zeros", "tensorflow.initializers.RandomNormal", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.reshape", "tensorflow.cast", "tensorflow.keras.datasets.mnist.load_data", "tensorflow.math.log", "tensorflow.one_hot", "tensorflow.optimizers.SGD", "tensorflow.argmax", "matplotlib.pyplot.show", "tensorflow.GradientTape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13", "1.10", "1.12" ] } ]
kevin3/cwl-ica
[ "cf706ea42993d563f364c0847ee4b882f8fe067c", "cf706ea42993d563f364c0847ee4b882f8fe067c", "cf706ea42993d563f364c0847ee4b882f8fe067c" ]
[ "src/subcommands/listers/list_users.py", "src/subcommands/listers/list_projects.py", "src/subcommands/listers/list_tenants.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"\nList all users registered in <CWL_ICA_REPO_PATH>/config/user.yaml\n\"\"\"\n\nfrom classes.command import Command\nfrom utils.logging import get_logger\nimport pandas as pd\nfrom utils.repo import read_yaml, get_user_yaml_path\nimport sys\n\nlogger = get_logger()\n\n\nclass ListUsers(Command):\n \"\"\"Usage:\n cwl-ica [options] list-users help\n cwl-ica [options] list-users\n\nDescription:\n List all registered users in <CWL_ICA_REPO_PATH>/config/user.yaml\n\nExample:\n cwl-ica list-users\n \"\"\"\n\n def __init__(self, command_argv):\n # Collect args from doc strings\n super().__init__(command_argv)\n\n # Check args\n self.check_args()\n\n def __call__(self):\n \"\"\"\n Just run through this\n :return:\n \"\"\"\n\n # Check project.yaml exists\n user_yaml_path = get_user_yaml_path()\n\n user_list = read_yaml(user_yaml_path)['users']\n\n # Create pandas df of user yaml path\n user_df = pd.DataFrame(user_list)\n\n # Write user to stdout\n user_df.to_markdown(sys.stdout, index=False)\n\n # Add new line\n print()\n\n def check_args(self):\n \"\"\"\n Check if --tenant-name is defined or CWL_ICA_DEFAULT_TENANT is present\n Or if --tenant-name is set to 'all'\n :return:\n \"\"\"\n\n # Just make sure the user.yaml path exists\n _ = get_user_yaml_path()\n", "#!/usr/bin/env python3\n\n\"\"\"\nList all projects registered in <CWL_ICA_REPO_PATH>/config/projects.yaml\n\"\"\"\n\nfrom classes.command import Command\nfrom utils.logging import get_logger\nimport pandas as pd\nfrom utils.repo import get_tenant_yaml_path, read_yaml, get_project_yaml_path\nimport os\nimport sys\nfrom utils.errors import TenantNotFoundError\n\nlogger = get_logger()\n\n\nclass ListProjects(Command):\n \"\"\"Usage:\n cwl-ica [options] list-projects help\n cwl-ica [options] list-projects [--tenant-name=<\"tenant_name\">]\n\nDescription:\n List all available projects, if --tenant-name is not set then tenants from all projects are returned.\n If env var CWL_ICA_DEFAULT_TENANT is set and you wish to view projects across all tenants, set --tenant-name to 'all'\n\nOptions:\n --tenant-name=<tenant name> Optional, filter by tenant-name.\n\nEnvironment Variables:\n CWL_ICA_DEFAULT_TENANT Can be used as an alternative for --tenant-name.\n\nExample:\n cwl-ica list-projects --tenant-name \"all\"\n cwl-ica list-projects --tenant-name \"tenant name\"\n cwl-ica list-projects\n \"\"\"\n\n def __init__(self, command_argv):\n # Collect args from doc strings\n super().__init__(command_argv)\n\n # Initialise values\n self.tenant_name = None\n\n # Check args\n self.check_args()\n\n def __call__(self):\n \"\"\"\n Just run through this\n :return:\n \"\"\"\n\n # Check project.yaml exists\n project_yaml_path = get_project_yaml_path()\n\n project_list = read_yaml(project_yaml_path)['projects']\n\n # Create pandas df of project yaml path\n project_df = pd.DataFrame(project_list)\n\n # Write project to stdout\n project_df[[\"project_name\", \"project_id\", \"project_description\", \"production\"]].\\\n to_markdown(sys.stdout, index=False)\n\n # Create a new line character\n print()\n\n def check_args(self):\n \"\"\"\n Check if --tenant-name is defined or CWL_ICA_DEFAULT_TENANT is present\n Or if --tenant-name is set to 'all'\n :return:\n \"\"\"\n\n tenant_arg = self.args.get(\"--tenant-name\", None)\n\n # Check if tenant arg is set\n if tenant_arg is None:\n tenant_arg = os.environ.get(\"CWL_ICA_DEFAULT_TENANT\", None)\n\n # Check if tenant arg is set to all\n if tenant_arg is None or tenant_arg == \"all\":\n self.tenant_name = None\n else:\n self.tenant_name = tenant_arg\n\n # If tenant_name is set, make sure it's present in tenant.yaml\n if self.tenant_name is not None:\n tenant_yaml_path = get_tenant_yaml_path()\n tenant_list = read_yaml(tenant_yaml_path)['tenants']\n for tenant in tenant_list:\n if tenant.get(\"tenant_name\", None) == self.tenant_name:\n break\n else:\n logger.error(f\"Tenant name set to \\\"{self.tenant_name}\\\" but \"\n f\"could not find this tenant name in \\\"{tenant_yaml_path}\\\"\\n\")\n raise TenantNotFoundError\n\n # Just make sure the project.yaml path exists\n _ = get_project_yaml_path()\n", "#!/usr/bin/env python3\n\n\"\"\"\nList all users registered in <CWL_ICA_REPO_PATH>/config/user.yaml\n\"\"\"\n\nfrom classes.command import Command\nfrom utils.logging import get_logger\nimport pandas as pd\nfrom utils.repo import read_yaml, get_tenant_yaml_path\nimport sys\n\nlogger = get_logger()\n\n\nclass ListTenants(Command):\n \"\"\"Usage:\n cwl-ica [options] list-tenants help\n cwl-ica [options] list-tenants\n\nDescription:\n List all registered tenants in <CWL_ICA_REPO_PATH>/config/tenant.yaml\n\nExample:\n cwl-ica list-users\n \"\"\"\n\n def __init__(self, command_argv):\n # Collect args from doc strings\n super().__init__(command_argv)\n\n # Check args\n self.check_args()\n\n def __call__(self):\n \"\"\"\n Just run through this\n :return:\n \"\"\"\n\n # Check project.yaml exists\n tenant_yaml_path = get_tenant_yaml_path()\n\n tenant_list = read_yaml(tenant_yaml_path)['tenants']\n\n # Create pandas df of tenant yaml path\n tenant_df = pd.DataFrame(tenant_list)\n\n # Write tenant to stdout\n tenant_df.to_markdown(sys.stdout, index=False)\n\n # Add new line\n print()\n\n def check_args(self):\n \"\"\"\n Check if --tenant-name is defined or CWL_ICA_DEFAULT_TENANT is present\n Or if --tenant-name is set to 'all'\n :return:\n \"\"\"\n\n # Just make sure the tenant.yaml path exists\n _ = get_tenant_yaml_path()\n" ]
[ [ "pandas.DataFrame" ], [ "pandas.DataFrame" ], [ "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": [] }, { "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": [ "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": [] } ]
Broly498/sentinel2-cloud-detector
[ "912880fcd6fed482475b4cd8da07bda17993ebe8" ]
[ "examples/plotting_utils.py" ]
[ "\"\"\"\nPlotting utilities for example notebooks\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plot_image(image=None, mask=None, ax=None, factor=3.5/255, clip_range=(0, 1), **kwargs):\n \"\"\" Utility function for plotting RGB images and masks.\n \"\"\"\n if ax is None:\n _, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 15))\n\n mask_color = [255, 255, 255, 255] if image is None else [255, 255, 0, 100]\n\n if image is None:\n if mask is None:\n raise ValueError('image or mask should be given')\n image = np.zeros(mask.shape + (3,), dtype=np.uint8)\n\n ax.imshow(np.clip(image * factor, *clip_range), **kwargs)\n\n if mask is not None:\n cloud_image = np.zeros((mask.shape[0], mask.shape[1], 4), dtype=np.uint8)\n\n cloud_image[mask == 1] = np.asarray(mask_color, dtype=np.uint8)\n\n ax.imshow(cloud_image)\n\n\ndef plot_probabilities(image, proba, factor=3.5/255):\n \"\"\" Utility function for plotting a RGB image and its cloud probability map next to each other.\n \"\"\"\n plt.figure(figsize=(15, 15))\n ax = plt.subplot(1, 2, 1)\n ax.imshow(np.clip(image * factor, 0, 1))\n plt.show\n ax = plt.subplot(1, 2, 2)\n ax.imshow(proba, cmap=plt.cm.inferno)\n plt.show\n\n" ]
[ [ "numpy.clip", "numpy.asarray", "matplotlib.pyplot.subplots", "matplotlib.pyplot.subplot", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
henrykironde/DeepForest
[ "9df98ea30debc8a1dc98edfa45dada063b109e6e" ]
[ "deepforest/preprocess.py" ]
[ "# Deepforest Preprocessing model\n\"\"\"The preprocessing module is used to reshape data into format suitable for\ntraining or prediction.\n\nFor example cutting large tiles into smaller images.\n\"\"\"\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport slidingwindow\nfrom PIL import Image\nimport torch\nimport warnings\nimport rasterio\n\ndef preprocess_image(image, device):\n \"\"\"Preprocess a single RGB numpy array as a prediction from channels last, to channels first\"\"\"\n image = torch.tensor(image, device=device).permute(2, 0, 1).unsqueeze(0)\n image = image / 255\n\n return image\n\n\ndef image_name_from_path(image_path):\n \"\"\"Convert path to image name for use in indexing.\"\"\"\n image_name = os.path.basename(image_path)\n image_name = os.path.splitext(image_name)[0]\n\n return image_name\n\n\ndef compute_windows(numpy_image, patch_size, patch_overlap):\n \"\"\"Create a sliding window object from a raster tile.\n\n Args:\n numpy_image (array): Raster object as numpy array to cut into crops\n\n Returns:\n windows (list): a sliding windows object\n \"\"\"\n\n if patch_overlap > 1:\n raise ValueError(\"Patch overlap {} must be between 0 - 1\".format(patch_overlap))\n\n # Generate overlapping sliding windows\n windows = slidingwindow.generate(numpy_image,\n slidingwindow.DimOrder.HeightWidthChannel,\n patch_size, patch_overlap)\n\n return (windows)\n\n\ndef select_annotations(annotations, windows, index, allow_empty=False):\n \"\"\"Select annotations that overlap with selected image crop.\n\n Args:\n image_name (str): Name of the image in the annotations file to lookup.\n annotations_file: path to annotations file in\n the format -> image_path, xmin, ymin, xmax, ymax, label\n windows: A sliding window object (see compute_windows)\n index: The index in the windows object to use a crop bounds\n allow_empty (bool): If True, allow window crops\n that have no annotations to be included\n\n Returns:\n selected_annotations: a pandas dataframe of annotations\n \"\"\"\n\n # Window coordinates - with respect to tile\n window_xmin, window_ymin, w, h = windows[index].getRect()\n window_xmax = window_xmin + w\n window_ymax = window_ymin + h\n\n # buffer coordinates a bit to grab boxes that might start just against\n # the image edge. Don't allow boxes that start and end after the offset\n offset = 40\n selected_annotations = annotations[(annotations.xmin > (window_xmin - offset)) &\n (annotations.xmin < (window_xmax)) &\n (annotations.xmax >\n (window_xmin)) & (annotations.ymin >\n (window_ymin - offset)) &\n (annotations.xmax <\n (window_xmax + offset)) & (annotations.ymin <\n (window_ymax)) &\n (annotations.ymax >\n (window_ymin)) & (annotations.ymax <\n (window_ymax + offset))]\n\n # change the image name\n image_name = os.path.splitext(\"{}\".format(annotations.image_path.unique()[0]))[0]\n image_basename = os.path.splitext(image_name)[0]\n selected_annotations.image_path = \"{}_{}.png\".format(image_basename, index)\n\n # If no matching annotations, return a line with the image name, but no\n # records\n if selected_annotations.empty:\n if allow_empty:\n selected_annotations = pd.DataFrame(\n [\"{}_{}.png\".format(image_basename, index)], columns=[\"image_path\"])\n selected_annotations[\"xmin\"] = 0\n selected_annotations[\"ymin\"] = 0\n selected_annotations[\"xmax\"] = 0\n selected_annotations[\"ymax\"] = 0\n #Dummy label\n selected_annotations[\"label\"] = annotations.label.unique()[0]\n else:\n return None\n else:\n # update coordinates with respect to origin\n selected_annotations.xmax = (selected_annotations.xmin - window_xmin) + (\n selected_annotations.xmax - selected_annotations.xmin)\n selected_annotations.xmin = (selected_annotations.xmin - window_xmin)\n selected_annotations.ymax = (selected_annotations.ymin - window_ymin) + (\n selected_annotations.ymax - selected_annotations.ymin)\n selected_annotations.ymin = (selected_annotations.ymin - window_ymin)\n\n # cut off any annotations over the border.\n selected_annotations.loc[selected_annotations.xmin < 0, \"xmin\"] = 0\n selected_annotations.loc[selected_annotations.xmax > w, \"xmax\"] = w\n selected_annotations.loc[selected_annotations.ymin < 0, \"ymin\"] = 0\n selected_annotations.loc[selected_annotations.ymax > h, \"ymax\"] = h\n\n return selected_annotations\n\n\ndef save_crop(base_dir, image_name, index, crop):\n \"\"\"Save window crop as image file to be read by PIL.\n\n Filename should match the image_name + window index\n \"\"\"\n # create dir if needed\n if not os.path.exists(base_dir):\n os.makedirs(base_dir)\n\n im = Image.fromarray(crop)\n image_basename = os.path.splitext(image_name)[0]\n filename = \"{}/{}_{}.png\".format(base_dir, image_basename, index)\n im.save(filename)\n\n return filename\n\n\ndef split_raster(annotations_file,\n path_to_raster=None,\n numpy_image=None,\n base_dir=\".\",\n patch_size=400,\n patch_overlap=0.05,\n allow_empty=False,\n image_name = None):\n \"\"\"Divide a large tile into smaller arrays. Each crop will be saved to\n file.\n\n Args:\n numpy_image: a numpy object to be used as a raster, usually opened from rasterio.open.read()\n path_to_raster: (str): Path to a tile that can be read by rasterio on disk\n annotations_file (str): Path to annotations file (with column names)\n data in the format -> image_path, xmin, ymin, xmax, ymax, label\n base_dir (str): Where to save the annotations and image\n crops relative to current working dir\n patch_size (int): Maximum dimensions of square window\n patch_overlap (float): Percent of overlap among windows 0->1\n allow_empty: If True, include images with no annotations\n to be included in the dataset\n image_name (str): If numpy_image arg is used, what name to give the raster?\n\n Returns:\n A pandas dataframe with annotations file for training.\n \"\"\"\n \n # Load raster as image\n # Load raster as image\n if (numpy_image is None) & (path_to_raster is None):\n raise IOError(\"supply a raster either as a path_to_raster or if ready from existing in memory numpy object, as numpy_image=\")\n \n if path_to_raster:\n numpy_image = rasterio.open(path_to_raster).read()\n numpy_image = np.moveaxis(numpy_image,0,2)\n else:\n if image_name is None:\n raise(IOError(\"If passing an numpy_image, please also specify a image_name to match the column in the annotation.csv file\"))\n\n # Check that its 3 band\n bands = numpy_image.shape[2]\n if not bands == 3:\n warnings.warn(\"Input rasterio had non-3 band shape of {}, ignoring alpha channel\".format(numpy_image.shape))\n try:\n numpy_image = numpy_image[:,:,:3].astype(\"uint8\") \n except:\n raise IOError(\"Input file {} has {} bands. DeepForest only accepts 3 band RGB \"\n \"rasters in the order (height, width, channels). Selecting the first three bands failed, please reshape manually.\"\n \"If the image was cropped and saved as a .jpg, \"\n \"please ensure that no alpha channel was used.\".format(\n path_to_raster, bands))\n\n # Check that patch size is greater than image size\n height = numpy_image.shape[0]\n width = numpy_image.shape[1]\n if any(np.array([height, width]) < patch_size):\n raise ValueError(\"Patch size of {} is larger than the image dimensions {}\".format(\n patch_size, [height, width]))\n\n # Compute sliding window index\n windows = compute_windows(numpy_image, patch_size, patch_overlap)\n\n # Get image name for indexing\n if image_name is None:\n image_name = os.path.basename(path_to_raster) \n\n # Load annotations file and coerce dtype\n annotations = pd.read_csv(annotations_file)\n\n # open annotations file\n image_annotations = annotations[annotations.image_path == image_name]\n\n # Sanity checks\n if image_annotations.empty:\n raise ValueError(\n \"No image names match between the file:{} and the image_path: {}. \"\n \"Reminder that image paths should be the relative \"\n \"path (e.g. 'image_name.tif'), not the full path \"\n \"(e.g. path/to/dir/image_name.tif)\".format(annotations_file, image_name))\n\n if not all([\n x in annotations.columns\n for x in [\"image_path\", \"xmin\", \"ymin\", \"xmax\", \"ymax\", \"label\"]\n ]):\n raise ValueError(\"Annotations file has {} columns, should have \"\n \"format image_path, xmin, ymin, xmax, ymax, label\".format(\n annotations.shape[1]))\n\n annotations_files = []\n for index, window in enumerate(windows):\n\n # Crop image\n crop = numpy_image[windows[index].indices()]\n \n #skip if empty crop\n if crop.size == 0:\n continue\n\n # Find annotations, image_name is the basename of the path\n crop_annotations = select_annotations(image_annotations, windows, index,\n allow_empty)\n\n # If empty images not allowed, select annotations returns None\n if crop_annotations is not None:\n # save annotations\n annotations_files.append(crop_annotations)\n\n # save image crop\n save_crop(base_dir, image_name, index, crop)\n if len(annotations_files) == 0:\n raise ValueError(\n \"Input file has no overlapping annotations and allow_empty is {}\".format(\n allow_empty))\n\n annotations_files = pd.concat(annotations_files)\n\n # Checkpoint csv files, useful for parallelization\n # Use filename of the raster path to save the annotations\n image_basename = os.path.splitext(image_name)[0]\n file_path = image_basename + \".csv\"\n file_path = os.path.join(base_dir, file_path)\n annotations_files.to_csv(file_path, index=False, header=True)\n\n return annotations_files\n" ]
[ [ "pandas.concat", "pandas.read_csv", "torch.tensor", "numpy.moveaxis", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
furkannturkmen/CS231n-2021
[ "2c6618d16bfd4e02e0493e8b8a411a6509206bb4" ]
[ "assignment2/cs231n/optim.py" ]
[ "import numpy as np\n\n\"\"\"\nThis file implements various first-order update rules that are commonly used\nfor training neural networks. Each update rule accepts current weights and the\ngradient of the loss with respect to those weights and produces the next set of\nweights. Each update rule has the same interface:\n\ndef update(w, dw, config=None):\n\nInputs:\n - w: A numpy array giving the current weights.\n - dw: A numpy array of the same shape as w giving the gradient of the\n loss with respect to w.\n - config: A dictionary containing hyperparameter values such as learning\n rate, momentum, etc. If the update rule requires caching values over many\n iterations, then config will also hold these cached values.\n\nReturns:\n - next_w: The next point after the update.\n - config: The config dictionary to be passed to the next iteration of the\n update rule.\n\nNOTE: For most update rules, the default learning rate will probably not\nperform well; however the default values of the other hyperparameters should\nwork well for a variety of different problems.\n\nFor efficiency, update rules may perform in-place updates, mutating w and\nsetting next_w equal to w.\n\"\"\"\n\n\ndef sgd(w, dw, config=None):\n \"\"\"\n Performs vanilla stochastic gradient descent.\n\n config format:\n - learning_rate: Scalar learning rate.\n \"\"\"\n if config is None:\n config = {}\n config.setdefault(\"learning_rate\", 1e-2)\n\n w -= config[\"learning_rate\"] * dw\n return w, config\n\n\ndef sgd_momentum(w, dw, config=None):\n \"\"\"\n Performs stochastic gradient descent with momentum.\n\n config format:\n - learning_rate: Scalar learning rate.\n - momentum: Scalar between 0 and 1 giving the momentum value.\n Setting momentum = 0 reduces to sgd.\n - velocity: A numpy array of the same shape as w and dw used to store a\n moving average of the gradients.\n \"\"\"\n if config is None:\n config = {}\n config.setdefault(\"learning_rate\", 1e-2)\n config.setdefault(\"momentum\", 0.9)\n v = config.get(\"velocity\", np.zeros_like(w))\n\n next_w = None\n ###########################################################################\n # TODO: Implement the momentum update formula. Store the updated value in #\n # the next_w variable. You should also use and update the velocity v. #\n ###########################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n \n v = v * config[\"momentum\"] - config[\"learning_rate\"] * dw # for example -> momentum = 0.9 lr = 0.1\n next_w = w + v\n \n\n \"\"\"\n v = config[\"momentum\"] * v + (1 - config[\"momentum\"]) * dw\n next_w = w - config[\"learning_rate\"] * v\n \"\"\"\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n config[\"velocity\"] = v\n\n return next_w, config\n\n\ndef rmsprop(w, dw, config=None):\n \"\"\"\n Uses the RMSProp update rule, which uses a moving average of squared\n gradient values to set adaptive per-parameter learning rates.\n\n config format:\n - learning_rate: Scalar learning rate.\n - decay_rate: Scalar between 0 and 1 giving the decay rate for the squared\n gradient cache.\n - epsilon: Small scalar used for smoothing to avoid dividing by zero.\n - cache: Moving average of second moments of gradients.\n \"\"\"\n if config is None:\n config = {}\n config.setdefault(\"learning_rate\", 1e-2)\n config.setdefault(\"decay_rate\", 0.99)\n config.setdefault(\"epsilon\", 1e-8)\n config.setdefault(\"cache\", np.zeros_like(w))\n\n next_w = None\n ###########################################################################\n # TODO: Implement the RMSprop update formula, storing the next value of w #\n # in the next_w variable. Don't forget to update cache value stored in #\n # config['cache']. #\n ###########################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n \"\"\"\n ADAGRAD\n \n config[\"cache\"] += dw * dw\n w = w - config[\"learning_rate\"] * dw / (np.sqrt(config[\"cache\"]) + config[\"epsilon\"])\n \"\"\"\n\n config[\"cache\"] = config[\"decay_rate\"] * config[\"cache\"] + (1 - config[\"decay_rate\"]) * dw * dw\n next_w = w - config[\"learning_rate\"] * dw / (np.sqrt(config[\"cache\"]) + config[\"epsilon\"])\n\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n\n return next_w, config\n\n\ndef adam(w, dw, config=None):\n \"\"\"\n Uses the Adam update rule, which incorporates moving averages of both the\n gradient and its square and a bias correction term.\n\n config format:\n - learning_rate: Scalar learning rate.\n - beta1: Decay rate for moving average of first moment of gradient.\n - beta2: Decay rate for moving average of second moment of gradient.\n - epsilon: Small scalar used for smoothing to avoid dividing by zero.\n - m: Moving average of gradient.\n - v: Moving average of squared gradient.\n - t: Iteration number.\n \"\"\"\n if config is None:\n config = {}\n config.setdefault(\"learning_rate\", 1e-3)\n config.setdefault(\"beta1\", 0.9)\n config.setdefault(\"beta2\", 0.999)\n config.setdefault(\"epsilon\", 1e-8)\n config.setdefault(\"m\", np.zeros_like(w))\n config.setdefault(\"v\", np.zeros_like(w))\n config.setdefault(\"t\", 0)\n\n next_w = None\n ###########################################################################\n # TODO: Implement the Adam update formula, storing the next value of w in #\n # the next_w variable. Don't forget to update the m, v, and t variables #\n # stored in config. #\n # #\n # NOTE: In order to match the reference output, please modify t _before_ #\n # using it in any calculations. #\n ###########################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n config[\"t\"] += 1\n # Momentum\n config[\"m\"] = config[\"beta1\"] * config[\"m\"] + (1 - config[\"beta1\"]) * dw\n m_unbias = config[\"m\"] / (1 - config[\"beta1\"] ** config[\"t\"])\n # RMSProp / ADAGRAD\n config[\"v\"] = config[\"beta2\"] * config[\"v\"] + (1 - config[\"beta2\"]) * dw ** 2\n v_unbias = config[\"v\"] / (1 - config[\"beta2\"] ** config[\"t\"])\n\n next_w = w - config[\"learning_rate\"] * m_unbias / (np.sqrt(v_unbias) + config[\"epsilon\"])\n\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n\n return next_w, config\n" ]
[ [ "numpy.zeros_like", "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kaikun213/fonduer-troy200
[ "d5653df48e3ce3037f4f1b500d454947ad0d010c" ]
[ "src/fonduer_utils.py" ]
[ "import emmental\nimport numpy as np\n\nfrom fonduer import Meta\nfrom emmental.modules.embedding_module import EmbeddingModule\nfrom emmental.data import EmmentalDataLoader\nfrom emmental.model import EmmentalModel\nfrom emmental.learner import EmmentalLearner\nfrom fonduer.learning.utils import collect_word_counter\nfrom fonduer.learning.dataset import FonduerDataset\nfrom fonduer.learning.task import create_task\nfrom troy200_utils import entity_level_f1\n\nABSTAIN = -1\nFALSE = 0\nTRUE = 1\n\ndef get_methods(ATTRIBUTE, gold, gold_file, all_docs):\n train_docs = all_docs[0]\n dev_docs = all_docs[1]\n test_docs = all_docs[2]\n\n def train_model(cands, F, align_type, model_type=\"LogisticRegression\"):\n # Extract candidates and features based on the align type (row/column)\n align_val = 0 if align_type == \"row\" else 1\n train_cands = cands[align_val][0]\n F_train = F[align_val][0]\n train_marginals = np.array([[0,1] if gold[align_val](x) else [1,0] for x in train_cands[0]])\n \n # 1.) Setup training config\n config = {\n \"meta_config\": {\"verbose\": True},\n \"model_config\": {\"model_path\": None, \"device\": 0, \"dataparallel\": False},\n \"learner_config\": {\n \"n_epochs\": 50,\n \"optimizer_config\": {\"lr\": 0.001, \"l2\": 0.0},\n \"task_scheduler\": \"round_robin\",\n },\n \"logging_config\": {\n \"evaluation_freq\": 1,\n \"counter_unit\": \"epoch\",\n \"checkpointing\": False,\n \"checkpointer_config\": {\n \"checkpoint_metric\": {f\"{ATTRIBUTE}/{ATTRIBUTE}/train/loss\": \"min\"},\n \"checkpoint_freq\": 1,\n \"checkpoint_runway\": 2,\n \"clear_intermediate_checkpoints\": True,\n \"clear_all_checkpoints\": True,\n },\n },\n }\n\n emmental.init(Meta.log_path)\n emmental.Meta.update_config(config=config)\n \n # 2.) Collect word counter from training data\n word_counter = collect_word_counter(train_cands)\n \n # 3.) Generate word embedding module for LSTM model\n # (in Logistic Regression, we generate it since Fonduer dataset requires word2id dict)\n # Geneate special tokens\n arity = 2\n specials = []\n for i in range(arity):\n specials += [f\"~~[[{i}\", f\"{i}]]~~\"]\n\n emb_layer = EmbeddingModule(\n word_counter=word_counter, word_dim=300, specials=specials\n )\n \n # 4.) Generate dataloader for training set\n # No noise in Gold labels\n train_dataloader = EmmentalDataLoader(\n task_to_label_dict={ATTRIBUTE: \"labels\"},\n dataset=FonduerDataset(\n ATTRIBUTE,\n train_cands[0],\n F_train[0],\n emb_layer.word2id,\n train_marginals,\n ),\n split=\"train\",\n batch_size=100,\n shuffle=True,\n )\n \n # 5.) Training \n tasks = create_task(\n ATTRIBUTE, 2, F_train[0].shape[1], 2, emb_layer, model=model_type # \"LSTM\" \n )\n\n model = EmmentalModel(name=f\"{ATTRIBUTE}_task\")\n\n for task in tasks:\n model.add_task(task)\n\n emmental_learner = EmmentalLearner()\n emmental_learner.learn(model, [train_dataloader])\n \n return (model, emb_layer)\n\n\n def eval_model(model, emb_layer, cands, F, align_type = \"row\"):\n # Extract candidates and features based on the align type (row/column)\n align_val = 0 if align_type == \"row\" else 1\n train_cands = cands[align_val][0]\n dev_cands = cands[align_val][1]\n test_cands = cands[align_val][2] \n F_train = F[align_val][0]\n F_dev = F[align_val][1]\n F_test = F[align_val][2]\n row_on = True if align_type == \"row\" else False\n col_on = True if align_type == \"col\" else False\n \n # Generate dataloader for test data\n test_dataloader = EmmentalDataLoader(\n task_to_label_dict={ATTRIBUTE: \"labels\"},\n dataset=FonduerDataset(\n ATTRIBUTE, test_cands[0], F_test[0], emb_layer.word2id, 2\n ),\n split=\"test\",\n batch_size=100,\n shuffle=False,\n )\n\n test_preds = model.predict(test_dataloader, return_preds=True)\n positive = np.where(np.array(test_preds[\"probs\"][ATTRIBUTE])[:, TRUE] > 0.6)\n true_pred = [test_cands[0][_] for _ in positive[0]]\n test_results = entity_level_f1(true_pred, gold_file, ATTRIBUTE, test_docs, row_on=row_on, col_on=col_on)\n \n # Run on dev and train set for validation\n # We run the predictions also on our training and dev set, to validate that everything seems to work smoothly\n \n # Generate dataloader for dev data\n dev_dataloader = EmmentalDataLoader(\n task_to_label_dict={ATTRIBUTE: \"labels\"},\n dataset=FonduerDataset(\n ATTRIBUTE, dev_cands[0], F_dev[0], emb_layer.word2id, 2\n ),\n split=\"test\",\n batch_size=100,\n shuffle=False,\n )\n\n\n dev_preds = model.predict(dev_dataloader, return_preds=True)\n positive_dev = np.where(np.array(dev_preds[\"probs\"][ATTRIBUTE])[:, TRUE] > 0.6)\n true_dev_pred = [dev_cands[0][_] for _ in positive_dev[0]]\n dev_results = entity_level_f1(true_dev_pred, gold_file, ATTRIBUTE, dev_docs, row_on=row_on, col_on=col_on)\n \n # Generate dataloader for train data\n train_dataloader = EmmentalDataLoader(\n task_to_label_dict={ATTRIBUTE: \"labels\"},\n dataset=FonduerDataset(\n ATTRIBUTE, train_cands[0], F_train[0], emb_layer.word2id, 2\n ),\n split=\"test\",\n batch_size=100,\n shuffle=False,\n )\n\n\n train_preds = model.predict(train_dataloader, return_preds=True)\n positive_train = np.where(np.array(train_preds[\"probs\"][ATTRIBUTE])[:, TRUE] > 0.6)\n true_train_pred = [train_cands[0][_] for _ in positive_train[0]]\n train_results = entity_level_f1(true_train_pred, gold_file, ATTRIBUTE, train_docs, row_on=row_on, col_on=col_on)\n \n return [train_results, dev_results, test_results]\n\n return (train_model, eval_model)" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
neptune-ai/examples
[ "e64cfaadb028e2187063fc43768dfee44074729b" ]
[ "integrations-and-supported-tools/optuna/scripts/Neptune_Optuna_integration_customize_callback.py" ]
[ "import lightgbm as lgb\nimport neptune.new as neptune\nimport neptune.new.integrations.optuna as optuna_utils\nimport optuna\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split\n\n\ndef objective(trial):\n data, target = load_breast_cancer(return_X_y=True)\n train_x, test_x, train_y, test_y = train_test_split(data, target, test_size=0.25)\n dtrain = lgb.Dataset(train_x, label=train_y)\n\n param = {\n \"verbose\": -1,\n \"objective\": \"binary\",\n \"metric\": \"binary_logloss\",\n \"num_leaves\": trial.suggest_int(\"num_leaves\", 2, 256),\n \"feature_fraction\": trial.suggest_uniform(\"feature_fraction\", 0.2, 1.0),\n \"bagging_fraction\": trial.suggest_uniform(\"bagging_fraction\", 0.2, 1.0),\n \"min_child_samples\": trial.suggest_int(\"min_child_samples\", 3, 100),\n }\n\n gbm = lgb.train(param, dtrain)\n preds = gbm.predict(test_x)\n accuracy = roc_auc_score(test_y, preds)\n\n return accuracy\n\n\n# Create a Neptune Run\nrun = neptune.init(\n api_token=\"ANONYMOUS\", project=\"common/optuna-integration\"\n) # you can pass your credentials here\n\n# Create a NeptuneCallback for Optuna\nneptune_callback = optuna_utils.NeptuneCallback(\n run,\n plots_update_freq=10,\n log_plot_slice=False,\n log_plot_contour=False,\n)\n\n# Pass NeptuneCallback to Optuna Study .optimize()\nstudy = optuna.create_study(direction=\"maximize\")\nstudy.optimize(objective, n_trials=50, callbacks=[neptune_callback])\n\n# Stop logging to a Neptune Run\nrun.stop()\n" ]
[ [ "sklearn.metrics.roc_auc_score", "sklearn.model_selection.train_test_split", "sklearn.datasets.load_breast_cancer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mttgdd/liegroups
[ "ca637bd461300d70d70f90bff7a18462d06f5f82" ]
[ "liegroups/torch/se2.py" ]
[ "import torch\n\nfrom . import _base\nfrom . import utils\nfrom .so2 import SO2Matrix\n\n\nclass SE2Matrix(_base.SEMatrixBase):\n \"\"\"See :mod:`liegroups.SE2`\"\"\"\n dim = 3\n dof = 3\n RotationType = SO2Matrix\n\n def adjoint(self):\n rot_part = self.rot.as_matrix()\n if rot_part.dim() < 3:\n rot_part = rot_part.unsqueeze(dim=0) # matrix --> batch\n\n trans = self.trans\n if trans.dim() < 2:\n # vector --> vectorbatch\n trans = trans.unsqueeze(dim=0)\n\n trans_part = trans.new_empty(\n trans.shape[0], trans.shape[1], 1)\n trans_part[:, 0, 0] = trans[:, 1]\n trans_part[:, 1, 0] = -trans[:, 0]\n\n bottom_row = trans.new_zeros(self.dof)\n bottom_row[-1] = 1.\n bottom_row = bottom_row.unsqueeze_(dim=0).unsqueeze_(\n dim=0).expand(trans.shape[0], 1, self.dof)\n\n return torch.cat([torch.cat([rot_part, trans_part], dim=2),\n bottom_row], dim=1).squeeze_()\n\n @classmethod\n def exp(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"xi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n rho = xi[:, 0:2]\n phi = xi[:, 2]\n\n rot = cls.RotationType.exp(phi)\n rot_jac = cls.RotationType.left_jacobian(phi)\n\n if rot_jac.dim() < 3:\n rot_jac.unsqueeze_(dim=0)\n if rho.dim() < 3:\n rho.unsqueeze_(dim=2)\n\n trans = torch.bmm(rot_jac, rho).squeeze_()\n\n return cls(rot, trans)\n\n @classmethod\n def inv_left_jacobian(cls, xi):\n\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"xi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n rho = xi[:, 0:2] # translation part\n phi = xi[:, 2] # rotation part\n\n cos_phi = torch.cos(phi)\n sin_phi = torch.sin(phi)\n phi_sq = phi * phi\n\n small_angle_mask = utils.isclose(phi_sq, 0.)\n small_angle_inds = small_angle_mask.nonzero().squeeze_(dim=1)\n\n large_angle_mask = small_angle_mask.logical_not()\n large_angle_inds = large_angle_mask.nonzero().squeeze_(dim=1)\n\n jac = torch.zeros((xi.shape[0], cls.dof, cls.dof)).to(xi.device)\n\n jac[small_angle_inds, 0, 0] = -(96*(phi_sq[small_angle_inds] - 6))/(phi_sq[small_angle_inds]**2*phi_sq[small_angle_inds] + 16*phi_sq[small_angle_inds]**2 - 24*phi_sq[small_angle_inds]*phi_sq[small_angle_inds] - 192*phi_sq[small_angle_inds] + 144*phi_sq[small_angle_inds] + 576)\n jac[small_angle_inds, 0, 1] = -(24*phi[small_angle_inds]*(phi_sq[small_angle_inds] - 12))/(phi_sq[small_angle_inds]**2*phi_sq[small_angle_inds] + 16*phi_sq[small_angle_inds]**2 - 24*phi_sq[small_angle_inds]*phi_sq[small_angle_inds] - 192*phi_sq[small_angle_inds] + 144*phi_sq[small_angle_inds] + 576)\n jac[small_angle_inds, 0, 2] = (4*(12*phi[small_angle_inds]*rho[small_angle_inds,0] - 72*rho[small_angle_inds,1] + 12*phi_sq[small_angle_inds]*rho[small_angle_inds,1] - 12*phi_sq[small_angle_inds]*rho[small_angle_inds,1] + phi_sq[small_angle_inds]*phi_sq[small_angle_inds]*rho[small_angle_inds,1] + phi_sq[small_angle_inds]*phi[small_angle_inds]*rho[small_angle_inds,0]))/(phi_sq[small_angle_inds]**2*phi_sq[small_angle_inds] + 16*phi_sq[small_angle_inds]**2 - 24*phi_sq[small_angle_inds]*phi_sq[small_angle_inds] - 192*phi_sq[small_angle_inds] + 144*phi_sq[small_angle_inds] + 576)\n jac[small_angle_inds, 1, 0] = (24*phi[small_angle_inds]*(phi_sq[small_angle_inds] - 12))/(phi_sq[small_angle_inds]**2*phi_sq[small_angle_inds] + 16*phi_sq[small_angle_inds]**2 - 24*phi_sq[small_angle_inds]*phi_sq[small_angle_inds] - 192*phi_sq[small_angle_inds] + 144*phi_sq[small_angle_inds] + 576)\n jac[small_angle_inds, 1, 1] = -(96*(phi_sq[small_angle_inds] - 6))/(phi_sq[small_angle_inds]**2*phi_sq[small_angle_inds] + 16*phi_sq[small_angle_inds]**2 - 24*phi_sq[small_angle_inds]*phi_sq[small_angle_inds] - 192*phi_sq[small_angle_inds] + 144*phi_sq[small_angle_inds] + 576)\n jac[small_angle_inds, 1, 2] = (4*(72*rho[small_angle_inds,0] - 12*phi_sq[small_angle_inds]*rho[small_angle_inds,0] + 12*phi[small_angle_inds]*rho[small_angle_inds,1] + 12*phi_sq[small_angle_inds]*rho[small_angle_inds,0] - phi_sq[small_angle_inds]*phi_sq[small_angle_inds]*rho[small_angle_inds,0] + phi_sq[small_angle_inds]*phi[small_angle_inds]*rho[small_angle_inds,1]))/(phi_sq[small_angle_inds]**2*phi_sq[small_angle_inds] + 16*phi_sq[small_angle_inds]**2 - 24*phi_sq[small_angle_inds]*phi_sq[small_angle_inds] - 192*phi_sq[small_angle_inds] + 144*phi_sq[small_angle_inds] + 576)\n\n jac[large_angle_inds, 0, 0] = (sin_phi[large_angle_inds]*phi[large_angle_inds])/(cos_phi[large_angle_inds]**2 - 2*cos_phi[large_angle_inds] + sin_phi[large_angle_inds]**2 + 1)\n jac[large_angle_inds, 0, 1] = -(phi[large_angle_inds]*(cos_phi[large_angle_inds] - 1))/(cos_phi[large_angle_inds]**2 - 2*cos_phi[large_angle_inds] + sin_phi[large_angle_inds]**2 + 1)\n jac[large_angle_inds, 0, 2] = (phi[large_angle_inds]*(rho[large_angle_inds,0] - 2*cos_phi[large_angle_inds]*rho[large_angle_inds,0] - phi[large_angle_inds]*rho[large_angle_inds,1] + cos_phi[large_angle_inds]**2*rho[large_angle_inds,0] + sin_phi[large_angle_inds]**2*rho[large_angle_inds,0] + cos_phi[large_angle_inds]*phi[large_angle_inds]*rho[large_angle_inds,1] - sin_phi[large_angle_inds]*phi[large_angle_inds]*rho[large_angle_inds,0]))/(phi_sq[large_angle_inds]*(cos_phi[large_angle_inds]**2 - 2*cos_phi[large_angle_inds] + sin_phi[large_angle_inds]**2 + 1))\n jac[large_angle_inds, 1, 0] = (phi[large_angle_inds]*(cos_phi[large_angle_inds] - 1))/(cos_phi[large_angle_inds]**2 - 2*cos_phi[large_angle_inds] + sin_phi[large_angle_inds]**2 + 1)\n jac[large_angle_inds, 1, 1] = (sin_phi[large_angle_inds]*phi[large_angle_inds])/(cos_phi[large_angle_inds]**2 - 2*cos_phi[large_angle_inds] + sin_phi[large_angle_inds]**2 + 1)\n jac[large_angle_inds, 1, 2] = (phi[large_angle_inds]*(rho[large_angle_inds,1] - 2*cos_phi[large_angle_inds]*rho[large_angle_inds,1] + phi[large_angle_inds]*rho[large_angle_inds,0] + cos_phi[large_angle_inds]**2*rho[large_angle_inds,1] + sin_phi[large_angle_inds]**2*rho[large_angle_inds,1] - cos_phi[large_angle_inds]*phi[large_angle_inds]*rho[large_angle_inds,0] - sin_phi[large_angle_inds]*phi[large_angle_inds]*rho[large_angle_inds,1]))/(phi_sq[large_angle_inds]*(cos_phi[large_angle_inds]**2 - 2*cos_phi[large_angle_inds] + sin_phi[large_angle_inds]**2 + 1))\n \n jac[:, 2, 0] = 0\n jac[:, 2, 1] = 0\n jac[:, 2, 2] = 1\n\n return jac.squeeze_()\n\n @classmethod\n def left_jacobian(cls, xi):\n\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"xi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n rho = xi[:, 0:2] # translation part\n phi = xi[:, 2] # rotation part\n\n cos_phi = torch.cos(phi)\n sin_phi = torch.sin(phi)\n phi_sq = phi * phi\n\n small_angle_mask = utils.isclose(phi_sq, 0.)\n small_angle_inds = small_angle_mask.nonzero().squeeze_(dim=1)\n\n large_angle_mask = small_angle_mask.logical_not()\n large_angle_inds = large_angle_mask.nonzero().squeeze_(dim=1)\n\n jac = torch.zeros((xi.shape[0], cls.dof, cls.dof)).to(xi.device)\n\n jac[small_angle_inds, 0, 0] = 1 - 1./6. * phi_sq[small_angle_inds]\n jac[small_angle_inds, 0, 1] = -(0.5 * phi[small_angle_inds] - 1./24. * phi[small_angle_inds] * phi_sq[small_angle_inds])\n jac[small_angle_inds, 0, 2] = rho[small_angle_inds,1] / 2. + phi[small_angle_inds] * rho[small_angle_inds,0] / 6.\n jac[small_angle_inds, 1, 0] = 0.5 * phi[small_angle_inds] - 1./24. * phi[small_angle_inds] * phi_sq[small_angle_inds]\n jac[small_angle_inds, 1, 1] = 1 - 1./6. * phi_sq[small_angle_inds]\n jac[small_angle_inds, 1, 2] = -rho[small_angle_inds,0] / 2. + phi[small_angle_inds] * rho[small_angle_inds,1] / 6.\n\n jac[large_angle_inds, 0, 0] = sin_phi[large_angle_inds] / phi[large_angle_inds]\n jac[large_angle_inds, 0, 1] = -(1 - cos_phi[large_angle_inds]) / phi[large_angle_inds]\n jac[large_angle_inds, 0, 2] = ( rho[large_angle_inds,1] + phi[large_angle_inds]*rho[large_angle_inds,0] - rho[large_angle_inds,1]*cos_phi[large_angle_inds] - rho[large_angle_inds,0]*sin_phi[large_angle_inds])/phi_sq[large_angle_inds]\n jac[large_angle_inds, 1, 0] = (1 - cos_phi[large_angle_inds]) / phi[large_angle_inds]\n jac[large_angle_inds, 1, 1] = sin_phi[large_angle_inds] / phi[large_angle_inds]\n jac[large_angle_inds, 1, 2] = (-rho[large_angle_inds,0] + phi[large_angle_inds]*rho[large_angle_inds,1] + rho[large_angle_inds,0]*cos_phi[large_angle_inds] - rho[large_angle_inds,1]*sin_phi[large_angle_inds])/phi_sq[large_angle_inds]\n\n jac[:, 2, 0] = 0\n jac[:, 2, 1] = 0\n jac[:, 2, 2] = 1\n\n return jac.squeeze_()\n\n def log(self):\n phi = self.rot.log()\n inv_rot_jac = self.RotationType.inv_left_jacobian(phi)\n\n if self.trans.dim() < 2:\n trans = self.trans.unsqueeze(dim=0)\n else:\n trans = self.trans\n\n if phi.dim() < 1:\n phi.unsqueeze_(dim=0)\n phi.unsqueeze_(dim=1) # because phi is 1-dimensional for SE2\n\n if inv_rot_jac.dim() < 3:\n inv_rot_jac.unsqueeze_(dim=0)\n if trans.dim() < 3:\n trans = trans.unsqueeze(dim=2)\n\n rho = torch.bmm(inv_rot_jac, trans).squeeze_()\n if rho.dim() < 2:\n rho.unsqueeze_(dim=0)\n\n return torch.cat([rho, phi], dim=1).squeeze_()\n\n @classmethod\n def odot(cls, p, directional=False):\n if p.dim() < 2:\n p = p.unsqueeze(dim=0) # vector --> vectorbatch\n\n result = p.__class__(p.shape[0], p.shape[1], cls.dof).zero_()\n\n # Got euclidean coordinates\n if p.shape[1] == cls.dim - 1:\n # Assume scale parameter is 1 unless p is a direction\n # vector, in which case the scale is 0\n if not directional:\n result[:, 0:2, 0:2] = torch.eye(\n cls.RotationType.dim).unsqueeze_(dim=0).expand(\n p.shape[0], cls.RotationType.dim, cls.RotationType.dim)\n\n result[:, 0:2, 2] = torch.mm(\n cls.RotationType.wedge(p.__class__([1.])),\n p.transpose(1, 0)).transpose_(1, 0)\n\n # Got homogeneous coordinates\n elif p.shape[1] == cls.dim:\n result[:, 0:2, 0:2] = \\\n p[:, 2].unsqueeze_(dim=1).unsqueeze_(dim=2) * \\\n torch.eye(\n cls.RotationType.dim).unsqueeze_(dim=0).repeat(\n p.shape[0], 1, 1)\n\n result[:, 0:2, 2] = torch.mm(\n cls.RotationType.wedge(p.__class__([1.])),\n p[:, 0:2].transpose_(1, 0)).transpose_(1, 0)\n\n # Got wrong dimension\n else:\n raise ValueError(\"p must have shape ({},), ({},), (N,{}) or (N,{})\".format(\n cls.dim - 1, cls.dim, cls.dim - 1, cls.dim))\n\n return result.squeeze_()\n\n @classmethod\n def vee(cls, Xi):\n if Xi.dim() < 3:\n Xi = Xi.unsqueeze(dim=0)\n\n if Xi.shape[1:3] != (cls.dim, cls.dim):\n raise ValueError(\"Xi must have shape ({},{}) or (N,{},{})\".format(\n cls.dim, cls.dim, cls.dim, cls.dim))\n\n xi = Xi.new_empty(Xi.shape[0], cls.dof)\n xi[:, 0:2] = Xi[:, 0:2, 2]\n xi[:, 2] = cls.RotationType.vee(Xi[:, 0:2, 0:2])\n\n return xi.squeeze_()\n\n @classmethod\n def wedge(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"phi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n Xi = xi.new_zeros(xi.shape[0], cls.dim, cls.dim)\n Xi[:, 0:2, 0:2] = cls.RotationType.wedge(xi[:, 2])\n Xi[:, 0:2, 2] = xi[:, 0:2]\n\n return Xi.squeeze_()\n" ]
[ [ "torch.cat", "torch.zeros", "torch.sin", "torch.eye", "torch.bmm", "torch.cos" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
972d5defe3218bd62b741e6a2f11f5b3/riptable
[ "bb928c11752e831ec701f91964979b31db53826a", "bb928c11752e831ec701f91964979b31db53826a", "bb928c11752e831ec701f91964979b31db53826a", "bb928c11752e831ec701f91964979b31db53826a" ]
[ "riptable/tests/test_scalar.py", "riptable/tests/test_accum2.py", "riptable/hypothesis_tests/test_riptide_numpy_equivalency.py", "riptable/benchmarks/bench_merge.py" ]
[ "\"\"\"Test around scalar constructors and scalar methods.\"\"\"\r\nimport riptable as rt\r\nimport numpy as np\r\nimport pytest\r\n\r\nfrom numpy.testing import assert_almost_equal, assert_warns\r\n\r\n\r\nclass TestScalarConstructor(object):\r\n # Type-coercion from strings test cases adapted from numpy/core/tests/test_scalar_ctors.py.\r\n # https://github.com/numpy/numpy/blob/c31cc36a8a814ed4844a2a553454185601914a5a/numpy/core/tests/test_scalar_ctors.py\r\n @pytest.mark.parametrize(\r\n \"scalar_ctor, numeric_string\",\r\n [\r\n # simple numeric string\r\n (\"single\", \"1.234\"),\r\n (\"double\", \"1.234\"),\r\n (\"longdouble\", \"1.234\"),\r\n # numeric string with overflow overflow; expect inf value\r\n (\"half\", \"1e10000\"),\r\n (\"single\", \"1e10000\"),\r\n (\"double\", \"1e10000\"),\r\n (\"longdouble\", \"1e10000\"),\r\n (\"longdouble\", \"-1e10000\"),\r\n ],\r\n )\r\n def test_floating(self, scalar_ctor, numeric_string):\r\n rt_value = getattr(rt, scalar_ctor)(numeric_string)\r\n np_value = getattr(np, scalar_ctor)(numeric_string)\r\n assert_almost_equal(rt_value, np_value)\r\n\r\n @pytest.mark.parametrize(\r\n \"scalar_ctor, numeric_string\",\r\n [(\"longdouble\", \"1e10000\"), (\"longdouble\", \"-1e10000\"),],\r\n )\r\n def test_overflow_warning(self, scalar_ctor, numeric_string):\r\n assert_warns(RuntimeWarning, getattr(np, scalar_ctor), numeric_string)\r\n", "import unittest\r\nimport pandas as pd\r\nimport pytest\r\n\r\nimport riptable as rt\r\n# N.B. TL;DR We have to import the actual implementation module to override the module global\r\n# variable \"tm.N\" and \"tm.K\".\r\n# In pandas 1.0 they move the code from pandas/util/testing.py to pandas/_testing.py.\r\n# The \"import pandas.util.testing\" still works but because it doesn't contain the actual code\r\n# our attempt to override the \"tm.N\" and \"tm.K\" will not change the actual value for\r\n# makeTimeDataFrame, which will produce data with different shape and make the test\r\n# \"test_accum_table\" fail. Maybe we want to reconsider using the pandas internal testing utils.\r\ntry:\r\n import pandas._testing as tm\r\nexcept ImportError:\r\n import pandas.util.testing as tm\r\n\r\nfrom riptable import *\r\nfrom numpy.testing import (\r\n assert_array_equal,\r\n assert_almost_equal,\r\n assert_array_almost_equal,\r\n)\r\nfrom riptable.rt_numpy import arange\r\n# To create AccumTable test data\r\nfrom riptable.Utils.pandas_utils import dataset_from_pandas_df\r\nfrom riptable.rt_datetime import DateTimeNano\r\n\r\n\r\ntm.N = 3\r\ntm.K = 5\r\n\r\n\r\nclass Accum2_Test(unittest.TestCase):\r\n '''\r\n TODO: add more tests for different types\r\n '''\r\n\r\n def test_accum2(self):\r\n c = cut(arange(10), 3)\r\n self.assertTrue(sum(c._np - FA([1, 1, 1, 1, 2, 2, 2, 3, 3, 3])) == 0)\r\n\r\n c = cut(arange(10.0), 3)\r\n self.assertTrue(sum(c._np - FA([1, 1, 1, 1, 2, 2, 2, 3, 3, 3])) == 0)\r\n\r\n c = cut(arange(11), 3)\r\n self.assertTrue(sum(c._np - FA([1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3])) == 0)\r\n\r\n c = cut(FA([2, 4, 6, 8, 10]), FA([0, 2, 4, 6, 8, 10]))\r\n self.assertTrue(sum(c._np - FA([1, 2, 3, 4, 5])) == 0)\r\n\r\n c = cut(\r\n FA([2, 4, 6, 8, 10]),\r\n FA([0, 2, 4, 6, 8, 10]),\r\n labels=['a', 'b', 'c', 'd', 'e'],\r\n )\r\n self.assertTrue(sum(c._np - FA([1, 2, 3, 4, 5])) == 0)\r\n\r\n def test_qcut(self):\r\n c = qcut(arange(10), 3)\r\n self.assertTrue(sum(c._np - FA([2, 2, 2, 2, 3, 3, 3, 4, 4, 4])) == 0)\r\n\r\n c = qcut(arange(11), 3)\r\n self.assertTrue(sum(c._np - FA([2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4])) == 0)\r\n\r\n c = qcut(range(5), 3, labels=[\"good\", \"medium\", \"bad\"])\r\n self.assertTrue(sum(c._np - FA([2, 2, 3, 4, 4])) == 0)\r\n\r\n c = cut(\r\n FA([2, 4, 6, 8, 10]),\r\n FA([0, 2, 4, 6, 8, 10]),\r\n labels=['a', 'b', 'c', 'd', 'e'],\r\n )\r\n\r\n def test_cut_errors(self):\r\n with self.assertRaises(ValueError):\r\n c = cut(\r\n FA([2, 4, 6, 8, 10]),\r\n FA([0, 2, 4, 6, 8, 10]),\r\n labels=['a', 'b', 'c', 'd', 'e', 'f'],\r\n )\r\n\r\n def test_simple_cats(self):\r\n data = arange(1, 6) * 10\r\n colnames = FastArray(['a', 'b', 'c', 'd', 'e'])\r\n c1 = Categorical(colnames)\r\n c2 = Categorical(arange(5))\r\n\r\n # no filter\r\n ac = Accum2(c2, c1)\r\n result = ac.sum(data)\r\n self.assertEqual(result._ncols, 7)\r\n for i, colname in enumerate(colnames):\r\n arr = result[colname]\r\n self.assertEqual(arr[i], data[i])\r\n\r\n def test_simple_cats_filter_accum(self):\r\n data = arange(1, 6) * 10\r\n colnames = FastArray(['a', 'b', 'c', 'd', 'e'])\r\n c1 = Categorical(colnames)\r\n c2 = Categorical(arange(5))\r\n\r\n # filtered accum object\r\n ac = Accum2(c2, c1, showfilter=True)\r\n result = ac.sum(data)\r\n self.assertEqual(result._ncols, 8)\r\n for i, colname in enumerate(colnames):\r\n arr = result[colname]\r\n self.assertEqual(arr[i + 1], data[i])\r\n\r\n def test_simple_cats_filter_operation(self):\r\n data = arange(1, 6) * 10\r\n colnames = FastArray(['a', 'b', 'c', 'd', 'e'])\r\n c1 = Categorical(colnames)\r\n c2 = Categorical(arange(5))\r\n\r\n # filtered operation\r\n ac = Accum2(c2, c1)\r\n result = ac.sum(data, showfilter=True)\r\n self.assertEqual(result._ncols, 8)\r\n for i, colname in enumerate(colnames):\r\n arr = result[colname]\r\n self.assertEqual(arr[i + 1], data[i])\r\n\r\n def test_multikey_cats(self):\r\n unsorted_str = FastArray(['c', 'e', 'b', 'd', 'a'])\r\n ints = arange(1, 6) * 10\r\n data = np.random.rand(5) * 10\r\n\r\n # unsorted no filter\r\n c1 = Categorical([unsorted_str, ints])\r\n c2 = Categorical([unsorted_str, ints])\r\n ac = Accum2(c2, c1)\r\n result = ac.sum(data)\r\n self.assertEqual(result._ncols, 8)\r\n for i, key1 in enumerate(unsorted_str):\r\n k1 = bytes.decode(key1)\r\n k2 = ints[i]\r\n full_colname = \"('\" + k1 + \"', \" + str(k2) + \")\"\r\n arr = result[full_colname]\r\n self.assertEqual(arr[i], data[i])\r\n\r\n # sorted no filter\r\n sortidx = np.argsort(unsorted_str)\r\n sorted_str = unsorted_str[sortidx]\r\n sorted_ints = ints[sortidx]\r\n sorted_data = data[sortidx]\r\n c1 = Categorical([unsorted_str, ints], ordered=True)\r\n c2 = Categorical([unsorted_str, ints], ordered=True)\r\n ac = Accum2(c2, c1)\r\n result = ac.sum(data)\r\n self.assertEqual(result._ncols, 8)\r\n for i, key1 in enumerate(sorted_str):\r\n k1 = bytes.decode(key1)\r\n k2 = sorted_ints[i]\r\n full_colname = \"('\" + k1 + \"', \" + str(k2) + \")\"\r\n arr = result[full_colname]\r\n self.assertEqual(arr[i], sorted_data[i])\r\n\r\n @pytest.mark.xfail(reason='20200416 This test was previously overridden by a later test in the file with the same name. Need to revisit and get back in a working state.')\r\n def test_multikey_cats_filter_accum_sorted(self):\r\n unsorted_str = FastArray(['c', 'e', 'b', 'd', 'a'])\r\n ints = arange(1, 6) * 10\r\n data = np.random.rand(5) * 10\r\n\r\n # unsorted filter accum object\r\n c1 = Categorical([unsorted_str, ints])\r\n c2 = Categorical([unsorted_str, ints])\r\n ac = Accum2(c2, c1, showfilter=True)\r\n result = ac.sum(data)\r\n self.assertEqual(result._ncols, 9)\r\n for i, key1 in enumerate(unsorted_str):\r\n k1 = bytes.decode(key1)\r\n k2 = ints[i]\r\n full_colname = \"('\" + k1 + \"', \" + str(k2) + \")\"\r\n arr = result[full_colname]\r\n self.assertEqual(arr[i + 1], data[i])\r\n\r\n # sorted filter accum object\r\n sortidx = np.argsort(unsorted_str)\r\n sorted_str = unsorted_str[sortidx]\r\n sorted_ints = ints[sortidx]\r\n sorted_data = data[sortidx]\r\n c1 = Categorical([unsorted_str, ints], sort_gb=True)\r\n c2 = Categorical([unsorted_str, ints], sort_gb=True)\r\n ac = Accum2(c2, c1, showfilter=True)\r\n result = ac.sum(data)\r\n self.assertEqual(result._ncols, 9)\r\n for i, key1 in enumerate(sorted_str):\r\n k1 = bytes.decode(key1)\r\n k2 = sorted_ints[i]\r\n full_colname = \"('\" + k1 + \"', \" + str(k2) + \")\"\r\n arr = result[full_colname]\r\n # TODO fix this regression that was masked due to duplicate test names\r\n # self.assertAlmostEqual(arr[i + 1], sorted_data[i])\r\n\r\n def test_multikey_cats_filter_accum_ordered(self):\r\n unsorted_str = FastArray(['c', 'e', 'b', 'd', 'a'])\r\n ints = arange(1, 6) * 10\r\n data = np.random.rand(5) * 10\r\n\r\n # unsorted filter accum object\r\n c1 = Categorical([unsorted_str, ints])\r\n c2 = Categorical([unsorted_str, ints])\r\n ac = Accum2(c2, c1)\r\n result = ac.sum(data, showfilter=True)\r\n self.assertEqual(result._ncols, 9)\r\n for i, key1 in enumerate(unsorted_str):\r\n k1 = bytes.decode(key1)\r\n k2 = ints[i]\r\n full_colname = \"('\" + k1 + \"', \" + str(k2) + \")\"\r\n arr = result[full_colname]\r\n self.assertEqual(arr[i + 1], data[i])\r\n\r\n # sorted filter accum object\r\n sortidx = np.argsort(unsorted_str)\r\n sorted_str = unsorted_str[sortidx]\r\n sorted_ints = ints[sortidx]\r\n sorted_data = data[sortidx]\r\n c1 = Categorical([unsorted_str, ints], ordered=True)\r\n c2 = Categorical([unsorted_str, ints], ordered=True)\r\n ac = Accum2(c2, c1)\r\n result = ac.sum(data, showfilter=True)\r\n self.assertEqual(result._ncols, 9)\r\n for i, key1 in enumerate(sorted_str):\r\n k1 = bytes.decode(key1)\r\n k2 = sorted_ints[i]\r\n full_colname = \"('\" + k1 + \"', \" + str(k2) + \")\"\r\n arr = result[full_colname]\r\n self.assertEqual(arr[i + 1], sorted_data[i])\r\n\r\n def test_dataset_accum2(self):\r\n # test from accum2 off dataset and with a filter\r\n ds = Dataset({'test': arange(10), 'data': arange(10) // 2})\r\n x = ds.accum2('data', 'test').sum(ds.test, filter=ds.data == 3)\r\n totalcol = x.summary_get_names()[0]\r\n self.assertEqual(x[totalcol][3], 13)\r\n\r\n def test_accum2_mean(self):\r\n ds = Dataset({'time': arange(200.0)})\r\n ds.data = np.random.randint(7, size=200)\r\n ds.data2 = np.random.randint(7, size=200)\r\n symbols = ['AAPL', 'AMZN', 'FB', 'GOOG', 'IBM']\r\n ds.symbol = Cat(1 + arange(200) % 5, symbols)\r\n ac = Accum2(ds.data, ds.symbol).mean(ds.time)\r\n totalcol = ac[ac.summary_get_names()[0]]\r\n footer = ac.footer_get_values()['Mean']\r\n for i in range(len(symbols)):\r\n s_mean = ds[ds.symbol == symbols[i], :].time.mean()\r\n self.assertEqual(footer[i + 1], s_mean)\r\n for i in range(7):\r\n s_mean = ds[ds.data == i, :].time.mean()\r\n self.assertEqual(totalcol[i], s_mean)\r\n\r\n def test_accum2_median(self):\r\n ds = Dataset({'time': arange(200.0)})\r\n ds.data = np.random.randint(7, size=200)\r\n ds.data2 = np.random.randint(7, size=200)\r\n symbols = ['AAPL', 'AMZN', 'FB', 'GOOG', 'IBM']\r\n ds.symbol = Cat(1 + arange(200) % 5, symbols)\r\n ac = Accum2(ds.data, ds.symbol).median(ds.time)\r\n totalcol = ac[ac.summary_get_names()[0]]\r\n footer = ac.footer_get_values()['Median']\r\n for i in range(len(symbols)):\r\n s_median = ds[ds.symbol == symbols[i], :].time.median()\r\n self.assertEqual(footer[i + 1], s_median)\r\n for i in range(7):\r\n s_median = ds[ds.data == i, :].time.median()\r\n self.assertEqual(totalcol[i], s_median)\r\n\r\n def test_accum2_nanmedian_with_filter(self):\r\n ds = Dataset({'time': arange(200.0)})\r\n ds.data = np.random.randint(7, size=200)\r\n ds.data2 = np.random.randint(7, size=200)\r\n symbols = ['AAPL', 'AMZN', 'FB', 'GOOG', 'IBM']\r\n # N.B. make a copy here for testing\r\n symbol_categorical = Cat(1 + arange(200) % 5, symbols)\r\n # N.B. Categorical.copy and Categorical constructor doesn't do deep copy?!\r\n ds.symbol = Cat(1 + arange(200) % 5, symbols)\r\n\r\n chosen_symbols = ['AMZN', 'AAPL']\r\n filt = symbol_categorical.isin(chosen_symbols)\r\n ac = Accum2(ds.data, ds.symbol)\r\n stat1 = ac.nanmedian(ds.time, filter=filt)\r\n totalcol = stat1[stat1.summary_get_names()[0]]\r\n footer = stat1.footer_get_values()['Median']\r\n # Make sure we don't change the input data\r\n self.assertTrue(not rt.any(ds.symbol._fa == 0))\r\n for sym in chosen_symbols:\r\n s_median = rt.nanmedian(ds[symbol_categorical == sym, :].time)\r\n i = rt.where(symbol_categorical.category_array == sym)[0].item()\r\n self.assertEqual(footer[i + 1], s_median)\r\n for i in range(7):\r\n s_median = rt.nanmedian(ds[(ds.data == i) & filt, :].time)\r\n self.assertEqual(totalcol[i], s_median)\r\n\r\n chosen_symbols = ['IBM', 'FB']\r\n filt = symbol_categorical.isin(chosen_symbols)\r\n stat2 = ac.nanmedian(ds.time, filter=filt)\r\n totalcol = stat2[stat2.summary_get_names()[0]]\r\n footer = stat2.footer_get_values()['Median']\r\n # Make sure we don't change the input data\r\n self.assertTrue(not rt.any(ds.symbol._fa == 0))\r\n for sym in chosen_symbols:\r\n s_median = rt.nanmedian(ds[symbol_categorical == sym, :].time)\r\n i = rt.where(symbol_categorical.category_array == sym)[0].item()\r\n self.assertEqual(footer[i + 1], s_median)\r\n for i in range(7):\r\n s_median = rt.nanmedian(ds[(ds.data == i) & filt, :].time)\r\n self.assertEqual(totalcol[i], s_median)\r\n\r\n def test_showfilter_label_subclass(self):\r\n d = Date.range('20190201', '20190210')\r\n c = Categorical(d)\r\n c2 = Categorical(arange(10))\r\n ac = Accum2(c, c2)\r\n result = ac.count(showfilter=True)\r\n\r\n self.assertTrue(isinstance(result.YLabel, Date))\r\n self.assertTrue(result.YLabel.isnan()[0])\r\n\r\n d = DateTimeNano.random(10)\r\n c = Categorical(d)\r\n c2 = Categorical(arange(10))\r\n ac = Accum2(c, c2)\r\n result = ac.count(showfilter=True)\r\n\r\n self.assertTrue(isinstance(result.YLabel, DateTimeNano))\r\n self.assertTrue(result.YLabel.isnan()[0])\r\n\r\n d = DateSpan(arange(10, 20))\r\n c = Categorical(d)\r\n c2 = Categorical(arange(10))\r\n ac = Accum2(c, c2)\r\n result = ac.count(showfilter=True)\r\n\r\n self.assertTrue(isinstance(result.YLabel, DateSpan))\r\n self.assertTrue(result.YLabel.isnan()[0])\r\n\r\n d = TimeSpan(np.random.rand(10) * 10_000_000_000)\r\n c = Categorical(d)\r\n c2 = Categorical(arange(10))\r\n ac = Accum2(c, c2)\r\n result = ac.count(showfilter=True)\r\n\r\n self.assertTrue(isinstance(result.YLabel, TimeSpan))\r\n self.assertTrue(result.YLabel.isnan()[0])\r\n\r\n def test_apply(self):\r\n arrsize = 200\r\n numrows = 7\r\n\r\n ds = Dataset({'time': arange(arrsize * 1.0)})\r\n ds.data = np.random.randint(numrows, size=arrsize)\r\n ds.data2 = np.random.randint(numrows, size=arrsize)\r\n symbols = ['AAPL', 'AMZN', 'FB', 'GOOG', 'IBM']\r\n ds.symbol = Cat(1 + arange(arrsize) % len(symbols), symbols)\r\n ds.accum2('symbol', 'data').sum(ds.data2)\r\n ds.accum2('symbol', 'data').sum(ds.data2, showfilter=True)\r\n ds.accum2('symbol', 'data').median(ds.data2, showfilter=True)\r\n ds.accum2('symbol', 'data').median(ds.data2, showfilter=False)\r\n ds.accum2('symbol', 'data').apply_reduce(np.median, ds.data2, showfilter=True)\r\n ds.accum2('symbol', 'data').apply_reduce(np.median, ds.data2, showfilter=False)\r\n f = logical(arange(200) % 2)\r\n ds.accum2('symbol', 'data').apply_reduce(np.median, ds.data2, filter=f)\r\n ds.accum2('symbol', 'data').apply_reduce(\r\n np.median, ds.data2, filter=f, showfilter=True\r\n )\r\n ds.accum2('symbol', 'data').median(ds.data2, filter=f, showfilter=True)\r\n\r\n def test_apply_nonreduce(self):\r\n arrsize = 200\r\n numrows = 7\r\n ds = rt.Dataset({'time': rt.arange(arrsize * 1.0)})\r\n ds.data = arange(arrsize) % numrows\r\n ds.data2 = (arange(arrsize) + 3) % numrows\r\n symbols = [\r\n 'AAPL',\r\n 'AMZN',\r\n 'FB',\r\n 'GOOG',\r\n 'IBM',\r\n '6',\r\n '7',\r\n '8',\r\n '9',\r\n '10',\r\n '11',\r\n '12',\r\n '13',\r\n '14',\r\n '15',\r\n '16',\r\n '17',\r\n '18',\r\n ]\r\n ds.symbol = rt.Cat(1 + rt.arange(arrsize) % len(symbols), symbols)\r\n result = ds.symbol.apply_reduce(\r\n lambda x, y: np.sum(np.minimum(x, y)), (ds.data, ds.data)\r\n )\r\n\r\n ac = ds.accum2('symbol', 'data')\r\n newds = ac.apply_nonreduce(np.cumsum)\r\n ds2 = ac.apply_reduce(\r\n lambda x, y: np.sum(np.maximum(x, y)), (newds.data, newds.data2)\r\n )\r\n\r\n x = np.maximum(newds.data, newds.data2)\r\n y = ac.apply_nonreduce(\r\n lambda x, y: np.maximum(x, y), (newds.data, newds.data2)\r\n )[0]\r\n self.assertTrue(np.all(x == y))\r\n\r\n\r\nclass AccumTable_Test(unittest.TestCase):\r\n @pytest.mark.skip(reason=\"Test needs to be re-written to remove the np.random.seed usage -- it's not stable across numpy versions.\")\r\n def test_accum_table(self):\r\n\r\n # Create the test data\r\n\r\n def unpivot(frame):\r\n N, K = frame.shape\r\n data = {\r\n 'value': frame.values.ravel('F'),\r\n 'variable': np.asarray(frame.columns).repeat(N),\r\n 'date': np.tile(np.asarray(frame.index), K),\r\n }\r\n return pd.DataFrame(data, columns=['date', 'variable', 'value'])\r\n\r\n np.random.seed(1234)\r\n df = unpivot(pd.concat([tm.makeTimeDataFrame(), tm.makeTimeDataFrame()]))\r\n ds = dataset_from_pandas_df(df)\r\n ds.date = DateTimeNano(ds.date, from_tz='NYC').to_iso()\r\n ds.date = rt.FastArray([d[:10] for d in ds.date])\r\n ds.variable = rt.Categorical(ds.variable)\r\n ds.date = rt.Categorical(ds.date)\r\n\r\n at = rt.AccumTable(ds.date, ds.variable)\r\n\r\n # Add and view inner tables with totals\r\n at['Sum'] = at.sum(ds.value)\r\n self.assertEqual(at['Sum'].shape, (3, 7))\r\n assert_array_almost_equal(\r\n at['Sum']['A'], np.array([0.47, -0.79, 1.72]), decimal=2\r\n )\r\n\r\n vw = at.gen('Sum')\r\n self.assertEqual(vw.shape, (3, 7))\r\n assert_array_almost_equal(vw['A'], np.array([0.47, -0.79, 1.72]), decimal=2)\r\n\r\n assert_array_almost_equal(vw['Sum'], np.array([-0.10, -5.02, 5.37]), decimal=2)\r\n assert_array_almost_equal(\r\n vw.footer_get_values(columns=['Sum'])['Sum'], np.array([0.25]), decimal=2\r\n )\r\n\r\n at['Mean'] = at.mean(ds.value)\r\n self.assertEqual(at['Mean'].shape, (3, 7))\r\n assert_array_almost_equal(\r\n at['Mean']['A'], np.array([0.24, -0.39, 0.86]), decimal=2\r\n )\r\n\r\n at['Half'] = at['Mean'] / at['Sum']\r\n self.assertEqual(at['Half'].shape, (3, 7))\r\n assert_array_almost_equal(at['Half']['A'], np.array([0.5, 0.5, 0.5]), decimal=2)\r\n\r\n # Add and view inner tables with blanks\r\n\r\n at['Blanks'] = at['Sum'].copy()\r\n at['Blanks']['C'] = 0.0\r\n for col in at['Blanks'][:, 1:]:\r\n at['Blanks'][col][2] = np.nan\r\n\r\n vw = at.gen('Blanks')\r\n self.assertEqual(vw.shape, (2, 9))\r\n assert_array_almost_equal(vw['A'], np.array([0.47, -0.79]), decimal=2)\r\n assert_array_almost_equal(vw['Blanks'], np.array([-0.10, -5.02]), decimal=2)\r\n self.assertAlmostEqual(\r\n vw.footer_get_dict()['Blanks']['Blanks'], 0.245, places=2\r\n )\r\n\r\n vw = at.gen('Blanks', remove_blanks=False)\r\n self.assertEqual(vw.shape, (3, 10))\r\n assert_array_almost_equal(vw['A'], np.array([0.47, -0.79, np.nan]), decimal=2)\r\n assert_array_almost_equal(\r\n vw['Blanks'], np.array([-0.10, -5.02, np.nan]), decimal=2\r\n )\r\n\r\n # Test division with zeros and nans\r\n at['Bad'] = at['Blanks'] / at['Half']\r\n self.assertEqual(at['Blanks'].shape, (3, 7))\r\n vw = at.gen('Bad')\r\n self.assertEqual(vw.shape, (2, 10))\r\n vw = at.gen('Blanks')\r\n self.assertEqual(vw.shape, (2, 10))\r\n vw = at.gen('Half')\r\n self.assertEqual(vw.shape, (3, 11))\r\n\r\n # Set margin columns to the right\r\n\r\n at.set_margin_columns(['Blanks', 'Mean'])\r\n vw = at.gen('Half')\r\n self.assertEqual(vw.shape, (3, 9))\r\n self.assertEqual(vw.keys()[6], 'Half')\r\n self.assertEqual(vw.keys()[7], 'Blanks')\r\n self.assertEqual(vw.keys()[8], 'Mean')\r\n self.assertEqual(\r\n list(vw.footer_get_dict().keys()), ['Half', 'Sum', 'Mean', 'Blanks', 'Bad']\r\n )\r\n\r\n vw = at.gen()\r\n self.assertEqual(vw.keys()[6], 'Half')\r\n\r\n vw = at.gen('Sum')\r\n self.assertEqual(vw.keys()[6], 'Sum')\r\n self.assertEqual(vw.keys()[7], 'Blanks')\r\n self.assertEqual(vw.keys()[8], 'Mean')\r\n self.assertEqual(\r\n list(vw.footer_get_dict().keys()), ['Sum', 'Mean', 'Half', 'Blanks', 'Bad']\r\n )\r\n\r\n # Set footer rows at the bottom\r\n\r\n at.set_footer_rows(['Mean'])\r\n vw = at.gen('Half')\r\n self.assertEqual(vw.shape, (3, 9))\r\n self.assertEqual(vw.keys()[6], 'Half')\r\n self.assertEqual(vw.keys()[7], 'Blanks')\r\n self.assertEqual(vw.keys()[8], 'Mean')\r\n self.assertEqual(list(vw.footer_get_dict().keys()), ['Half', 'Mean'])\r\n\r\n vw = at.gen('Sum')\r\n self.assertEqual(vw.keys()[6], 'Sum')\r\n self.assertEqual(vw.keys()[7], 'Blanks')\r\n self.assertEqual(vw.keys()[8], 'Mean')\r\n self.assertEqual(list(vw.footer_get_dict().keys()), ['Sum', 'Mean'])\r\n\r\n # Access view Dataset elements\r\n\r\n vw = at.gen('Sum')\r\n assert_array_equal(\r\n vw.date, rt.FastArray(['2000-01-03', '2000-01-04', '2000-01-05'])\r\n )\r\n assert_array_almost_equal(vw['Sum'], np.array([-0.10, -5.02, 5.37]), decimal=2)\r\n assert_almost_equal(vw[vw.date == '2000-01-03', 'A'][0], 0.47355353, decimal=2)\r\n assert_almost_equal(\r\n list(vw.footer_get_values('Sum', columns=['A']).values())[0],\r\n 1.409830,\r\n decimal=2,\r\n )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n tester = unittest.main()\r\n", "# TODO add test cases for half, single, and longdouble functions.\r\n# TODO add test cases for equivalent dtypes: bool_, bytes_, str_, int0, and uint0.\r\n# TODO add test cases for mask operations: mask_or, mask_and, mask_xor, mask_andnot, mask_ori, mask_andi, mask_xori, and mask_andnoti.\r\n# TODO fold all int, uint and float equivalence tests into one method that uses pytest parameters\r\nimport builtins\r\nimport operator\r\nimport random\r\nimport numpy as np\r\nimport riptable as rt\r\nimport pytest\r\nimport hypothesis\r\nfrom typing import List\r\nfrom riptable import FastArray, FA\r\nfrom numpy.testing import assert_allclose\r\nfrom hypothesis import assume, event, example, given, HealthCheck\r\nfrom hypothesis.extra.numpy import (\r\n arrays,\r\n basic_indices,\r\n boolean_dtypes,\r\n floating_dtypes,\r\n integer_dtypes,\r\n)\r\nfrom hypothesis.strategies import (\r\n integers,\r\n booleans,\r\n shared,\r\n data,\r\n lists,\r\n floats,\r\n sampled_from,\r\n slices,\r\n text,\r\n)\r\n\r\n# riptable custom Hypothesis strategies\r\nfrom .strategies.helper_strategies import (\r\n _MAX_FLOAT,\r\n _MAX_INT,\r\n _MAX_VALUE,\r\n floating_scalar,\r\n generate_array_and_axis,\r\n generate_array_and_where,\r\n generate_array_axis_and_ddof,\r\n generate_array_axis_and_repeats_array,\r\n generate_reshape_array_and_shape_strategy,\r\n generate_sample_test_floats,\r\n generate_sample_test_integers,\r\n generate_tuples_of_arrays,\r\n interpolation_data,\r\n ints_floats_complex_or_booleans,\r\n ints_floats_datetimes_and_timedeltas,\r\n ints_floats_or_complex_dtypes,\r\n ints_or_floats_dtypes,\r\n ints_or_floats_example,\r\n ndarray_shape_strategy,\r\n one_darray_shape_strategy,\r\n same_structure_ndarrays,\r\n start_stop_step_strategy,\r\n _MAX_SHAPE_SIZE,\r\n)\r\nfrom riptable.Utils.rt_testing import (\r\n assert_array_equal_,\r\n assert_equal_,\r\n _NDARRAY_FASTARRAY_COMMON_AND_DIFF,\r\n)\r\nfrom riptable.Utils.teamcity_helper import is_running_in_teamcity\r\n\r\n\r\n\"\"\"\r\nCommonalities between riptable and numpy\r\n>> import numpy as np\r\n>> import riptable as rt\r\n>> sorted(list(set(dir(rt)).intersection(set(dir(np)))))\r\n>> ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'abs', 'absolute', 'all', 'any', 'arange', 'argsort', 'bincount', 'ceil', 'concatenate', 'cumsum', 'diff', 'double', 'empty', 'empty_like', 'float32', 'float64', 'floor', 'full', 'hstack', 'int16', 'int32', 'int64', 'int8', 'interp', 'isfinite', 'isinf', 'isnan', 'lexsort', 'log', 'log10', 'max', 'maximum', 'mean', 'median', 'min', 'minimum', 'nan', 'nan_to_num', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanstd', 'nansum', 'nanvar', 'ones', 'ones_like', 'percentile', 'putmask', 'quantile', 'repeat', 'reshape', 'round', 'searchsorted', 'single', 'size', 'sort', 'std', 'sum', 'tile', 'transpose', 'trunc', 'uint16', 'uint32', 'uint64', 'uint8', 'unique', 'var', 'vstack', 'where', 'zeros', 'zeros_like']\r\n\"\"\"\r\n\r\n\r\nclass TestRiptableNumpyEquivalency:\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6479 abs calls np.abs instead of rt.absolute\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr_and_where=generate_array_and_where(\r\n shape=ndarray_shape_strategy(), dtype=ints_or_floats_dtypes()\r\n )\r\n )\r\n def test_abs(self, arr_and_where):\r\n arr, where_arr = arr_and_where\r\n\r\n # Test #1: Returns new array containing results; no optional parameters provided.\r\n rt_abs = rt.abs(arr)\r\n np_abs = np.abs(arr)\r\n assert isinstance(rt_abs, FastArray)\r\n assert_array_equal_(np.array(rt_abs), np_abs)\r\n\r\n # Test #2: Returns new array containing results; 'where' bitmask is provided.\r\n rt_abs = rt.abs(arr, where=where_arr)\r\n np_abs = np.abs(arr, where=where_arr)\r\n assert isinstance(rt_abs, FastArray)\r\n assert_array_equal_(np.array(rt_abs), np_abs)\r\n\r\n # Test #3: Results written to array specified in 'out' parameter; no other optional params.\r\n rt_abs = np.zeros_like(arr)\r\n np_abs = np.zeros_like(arr)\r\n rt_output = rt.abs(arr, out=rt_abs)\r\n np_output = np.abs(arr, out=np_abs)\r\n assert_array_equal_(np.array(rt_abs), np_abs)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.abs() did not return a FastArray\")\r\n\r\n # Test #4: Results written to array specified in 'out' parameter; 'where' bitmask is provided.\r\n rt_abs = np.zeros_like(arr)\r\n np_abs = np.zeros_like(arr)\r\n rt_output = rt.abs(arr, where=where_arr, out=rt_abs)\r\n np_output = np.abs(arr, where=where_arr, out=np_abs)\r\n assert_array_equal_(np.array(rt_abs), np_abs)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.abs() did not return a FastArray\")\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/RIP-357 discrepency between rt.absolute and np.absolute\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr_and_where=generate_array_and_where(\r\n shape=ndarray_shape_strategy(), dtype=ints_or_floats_dtypes()\r\n )\r\n )\r\n def test_absolute(self, arr_and_where):\r\n arr, where_arr = arr_and_where\r\n\r\n # Test #1: Returns new array containing results; no optional parameters provided.\r\n rt_output = rt.absolute(arr)\r\n np_output = np.absolute(arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #2: Returns new array containing results; 'where' bitmask is provided.\r\n rt_output = rt.absolute(arr, where=where_arr)\r\n np_absolute = np.absolute(arr, where=where_arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #3: Results written to array specified in 'out' parameter; no other optional params.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.absolute(arr, out=rt_inplace)\r\n np_output = np.absolute(arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.absolute() did not return a FastArray\")\r\n\r\n # Test #4: Results written to array specified in 'out' parameter; 'where' bitmask is provided.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.absolute(arr, where=where_arr, out=rt_inplace)\r\n np_output = np.absolute(arr, where=where_arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.absolute() did not return a FastArray\")\r\n\r\n @given(\r\n arr_and_axis=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_complex_or_booleans()\r\n )\r\n )\r\n def test_all(self, arr_and_axis):\r\n arr = arr_and_axis[0]\r\n axis = arr_and_axis[1]\r\n rt_all = rt.all(arr, axis=axis)\r\n np_all = np.all(arr, axis=axis)\r\n if axis is None:\r\n # If axis is None, all is performed on entire matrix, so it should have the same result as the builtin all()\r\n built_in_all = builtins.all(arr.flatten())\r\n assert rt_all == built_in_all\r\n assert rt_all == np_all\r\n else:\r\n # if performing all() over a certain axis, it will return an array/matrix\r\n assert_array_equal_(np.array(rt_all), np_all)\r\n\r\n @given(\r\n arr_and_axis=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_complex_or_booleans()\r\n )\r\n )\r\n def test_any(self, arr_and_axis):\r\n arr = arr_and_axis[0]\r\n axis = arr_and_axis[1]\r\n rt_any = rt.any(arr, axis=axis)\r\n np_any = np.any(arr, axis=axis)\r\n if axis is None:\r\n # If axis is None, any is performed on entire matrix, so it should have the same result as the builtin any()\r\n built_in_any = builtins.any(arr.flatten())\r\n assert rt_any == built_in_any\r\n assert rt_any == np_any\r\n else:\r\n # if performing any() over a certain axis, it will return an array/matrix\r\n assert_array_equal_(np.array(rt_any), np_any)\r\n\r\n @hypothesis.settings(suppress_health_check=[HealthCheck.too_slow])\r\n @example(\r\n start_stop_step={\r\n \"start\": (-1000000 - 1000000j),\r\n \"stop\": (1000000 + 1000000j),\r\n \"step\": (0.0000001 + 0.0000001j),\r\n }\r\n )\r\n @given(start_stop_step_strategy())\r\n def test_arange(self, start_stop_step):\r\n start = start_stop_step[\"start\"]\r\n stop = start_stop_step[\"stop\"]\r\n step = start_stop_step[\"step\"]\r\n\r\n # This block is instead of the assume(length < MAX_VALUE) so the example can be used to test large\r\n # numbers and complex numbers.\r\n min_step = abs((stop - start) / _MAX_VALUE)\r\n if min_step > abs(step):\r\n step = (step / abs(step)) * min_step\r\n\r\n # Compare results of arange and exception message, if one is thrown.\r\n rt_error_msg = \"\"\r\n np_error_msg = \"\"\r\n try:\r\n rt_arange = rt.arange(start, stop, step)\r\n except Exception as e:\r\n rt_arange = None\r\n rt_error_msg = str(e)\r\n try:\r\n np_arange = np.arange(start, stop, step)\r\n except Exception as e:\r\n np_arange = None\r\n np_error_msg = str(e)\r\n\r\n if rt_error_msg and np_error_msg:\r\n assert rt_error_msg == np_error_msg\r\n else:\r\n assert_array_equal_(np.array(rt_arange), np_arange)\r\n assert isinstance(rt_arange, FastArray)\r\n\r\n # TODO: Delete this test once SOQTEST-6495 is resolved. This way arange's main functionality can still be tested\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6495 kwargs not implemented in riptable.arange()\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(start_stop_step_strategy())\r\n def test_arange_kwargs(self, start_stop_step):\r\n start = start_stop_step[\"start\"]\r\n stop = start_stop_step[\"stop\"]\r\n step = start_stop_step[\"step\"]\r\n # limit step size so lists don't get too long and use up too many resources\r\n # These can be smaller than in test_arange, because this one is just confirming the kwargs work\r\n max_length = 1000\r\n length = abs((stop - start) / step)\r\n # TODO directly draw from this range, instead of using hypothesis assume\r\n assume(-1 <= length < max_length)\r\n rt_error_msg = \"\"\r\n np_error_msg = \"\"\r\n try:\r\n rt_arange = rt.arange(start=start, stop=stop, step=step)\r\n except Exception as e:\r\n rt_arange = None\r\n rt_error_msg = str(e)\r\n try:\r\n np_arange = np.arange(start=start, stop=stop, step=step)\r\n except Exception as e:\r\n np_arange = None\r\n np_error_msg = str(e)\r\n\r\n if rt_error_msg and np_error_msg:\r\n assert rt_error_msg == np_error_msg\r\n else:\r\n assert_array_equal_(np.array(rt_arange), np_arange)\r\n assert isinstance(rt_arange, FastArray)\r\n\r\n @given(\r\n arrays(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_datetimes_and_timedeltas()\r\n )\r\n )\r\n @pytest.mark.skip(reason=\"Skip if riptable defers to numpy argsort implementation.\")\r\n def test_argsort(self, arr):\r\n axis_list = [None]\r\n axis_list.extend(list(range(-1, len(arr.shape))))\r\n sort_algs = [\"quicksort\", \"mergesort\", \"heapsort\", \"stable\"]\r\n\r\n for axis in axis_list:\r\n for sort_alg in sort_algs:\r\n rt_argsort = rt.argsort(arr, axis=axis, kind=sort_alg)\r\n np_argsort = np.argsort(arr, axis=axis, kind=sort_alg)\r\n assert isinstance(rt_argsort, FastArray)\r\n assert_array_equal_(np.array(rt_argsort), np_argsort)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6497 riptable.bincount returns numpy array instead of FastArray\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(dtype=integer_dtypes(), shape=ndarray_shape_strategy(max_rank=1)),\r\n use_weights=booleans(),\r\n min_length=integers(),\r\n data=data(),\r\n )\r\n def test_bincount(self, data, arr, use_weights, min_length):\r\n weights = None\r\n if use_weights:\r\n weights = data.draw(arrays(dtype=integer_dtypes(), shape=arr.shape))\r\n rt_err = np_err = rt_bincount = np_bincount = None\r\n\r\n try:\r\n rt_bincount = rt.bincount(arr, weights=weights, minlength=min_length)\r\n except Exception as e:\r\n rt_err = str(e)\r\n\r\n try:\r\n np_bincount = np.bincount(arr, weights=weights, minlength=min_length)\r\n except Exception as e:\r\n np_err = str(e)\r\n\r\n # TODO re-visit this implementation since if-clause will evaluate when there are no exception\r\n if rt_err is None or np_err is None:\r\n assert rt_err == np_err\r\n else:\r\n assert_array_equal_(np.array(rt_bincount), np_bincount)\r\n assert isinstance(rt_bincount, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"Related to https://jira/browse/SOQTEST-6478 different endiannesses not handled\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n data=data(),\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(sizes=(32, 64))\r\n ),\r\n )\r\n def test_ceil_array(self, data, arr):\r\n # TODO: Modify this to use the 'generate_array_and_where' strategy instead?\r\n where_arr = data.draw(arrays(shape=arr.shape, dtype=boolean_dtypes()))\r\n\r\n # Test #1: Returns new array containing results; no optional parameters provided.\r\n rt_output = rt.ceil(arr)\r\n np_output = np.ceil(arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #2: Returns new array containing results; 'where' bitmask is provided.\r\n rt_output = rt.ceil(arr, where=where_arr)\r\n np_output = np.ceil(arr, where=where_arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #3: Results written to array specified in 'out' parameter; no other optional params.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.ceil(arr, out=rt_inplace)\r\n np_output = np.ceil(arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.ceil() did not return a FastArray\")\r\n\r\n # Test #4: Results written to array specified in 'out' parameter; 'where' bitmask is provided.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.ceil(arr, where=where_arr, out=rt_inplace)\r\n np_output = np.ceil(arr, where=where_arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.ceil() did not return a FastArray\")\r\n\r\n @given(scalar=floating_scalar())\r\n def test_ceil_scalar(self, scalar):\r\n # test scalars\r\n rt_ceil_scalar = rt.ceil(scalar)\r\n np_ceil_scalar = np.ceil(scalar)\r\n assert_equal_(rt_ceil_scalar, np_ceil_scalar)\r\n\r\n # TODO fold the concatenate tests by using pytest params.\r\n # 20200303 N.B, rt.concatenate defers to np.concatenate.\r\n @hypothesis.settings(suppress_health_check=[HealthCheck.too_slow])\r\n @example(tuple_of_arrays=tuple())\r\n @given(tuple_of_arrays=generate_tuples_of_arrays(all_same_width=True))\r\n def test_concatenate_first_axis(self, tuple_of_arrays):\r\n rt_err_type = np_err_type = rt_concatenate = np_concatenate = None\r\n\r\n # Capture the output if evaluation succeeds, otherwise capture the error type.\r\n try:\r\n rt_concatenate = rt.concatenate(tuple_of_arrays, axis=0)\r\n except Exception as e:\r\n rt_err_type = type(e)\r\n try:\r\n np_concatenate = np.concatenate(tuple_of_arrays, axis=0)\r\n except Exception as e:\r\n np_err_type = type(e)\r\n\r\n # The concatenated arrays should be equal to a tolerance and if any exceptions were raised\r\n # they should be the same type.\r\n if rt_err_type and np_err_type:\r\n assert rt_err_type == np_err_type\r\n else:\r\n assert isinstance(rt_concatenate, FastArray)\r\n assert_array_equal_(np.array(rt_concatenate), np_concatenate)\r\n\r\n @hypothesis.settings(suppress_health_check=[HealthCheck.too_slow])\r\n @example(tuple_of_arrays=tuple())\r\n @given(tuple_of_arrays=generate_tuples_of_arrays(all_same_width=True))\r\n def test_concatenate_flatten(self, tuple_of_arrays):\r\n rt_err_type = np_err_type = rt_concatenate = np_concatenate = None\r\n\r\n # Capture the output if evaluation succeeds, otherwise capture the error type.\r\n try:\r\n rt_concatenate = rt.concatenate(tuple_of_arrays, axis=None)\r\n except Exception as e:\r\n rt_err_type = type(e)\r\n try:\r\n np_concatenate = np.concatenate(tuple_of_arrays, axis=None)\r\n except Exception as e:\r\n np_err_type = type(e)\r\n\r\n # The concatenated arrays should be equal to a tolerance and if any exceptions were raised\r\n # they should be the same type.\r\n if rt_err_type and np_err_type:\r\n assert rt_err_type == np_err_type, f\"Exceptions should be the same type.\"\r\n else:\r\n assert isinstance(rt_concatenate, FastArray)\r\n assert_array_equal_(np.array(rt_concatenate), np_concatenate)\r\n\r\n @hypothesis.settings(suppress_health_check=[HealthCheck.too_slow])\r\n @example(tuple_of_arrays=tuple())\r\n @given(tuple_of_arrays=generate_tuples_of_arrays(all_same_height=True))\r\n def test_concatenate_second_axis(self, tuple_of_arrays):\r\n rt_err_type = np_err_type = rt_concatenate = np_concatenate = None\r\n\r\n # Capture the output if evaluation succeeds, otherwise capture the error type.\r\n try:\r\n rt_concatenate = rt.concatenate(tuple_of_arrays, axis=1)\r\n except ValueError as e:\r\n rt_err_type = ValueError\r\n try:\r\n np_concatenate = np.concatenate(tuple_of_arrays, axis=1)\r\n except ValueError as e:\r\n np_err_type = ValueError\r\n\r\n # The concatenated arrays should be equal to a tolerance and if any exceptions were raised\r\n # they should be the same type.\r\n if rt_err_type and np_err_type:\r\n assert rt_err_type == np_err_type\r\n else:\r\n assert isinstance(rt_concatenate, FastArray)\r\n assert_array_equal_(np.array(rt_concatenate), np_concatenate)\r\n\r\n @given(\r\n array_and_axis=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_or_complex_dtypes()\r\n ),\r\n output_dtype=ints_floats_or_complex_dtypes(),\r\n )\r\n def test_cumsum(self, array_and_axis, output_dtype):\r\n arr, axis = array_and_axis\r\n\r\n output_dtype = output_dtype\r\n rt_cumsum = rt.cumsum(arr, axis=axis) # 20200303 defers to numpy\r\n np_cumsum = np.cumsum(arr, axis=axis)\r\n assert isinstance(rt_cumsum, FastArray)\r\n assert_array_equal_(np.array(rt_cumsum), np_cumsum)\r\n\r\n rt_cumsum = rt.cumsum(arr, axis=axis, dtype=output_dtype)\r\n np_cumsum = np.cumsum(arr, axis=axis, dtype=output_dtype)\r\n assert isinstance(rt_cumsum, FastArray)\r\n assert (\r\n rt_cumsum.dtype == output_dtype\r\n ), f\"Dtype should be the same as input array.\"\r\n assert_array_equal_(np.array(rt_cumsum), np_cumsum)\r\n\r\n @given(\r\n array_and_axis=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(),\r\n dtype=ints_floats_or_complex_dtypes(),\r\n # If not specified, np.diff uses -1 as the default axis.\r\n default_axis=-1\r\n ),\r\n # 'diff_iters': the number of differencing iterations the 'diff' function will perform.\r\n # This is kind of like the \"divided differences\" algorithm in that it's recursive, but\r\n # there's no division step. Specifying a large number of iterations for this is prohibitively\r\n # expensive and will cause the test to time out; we can test with a small-ish number of\r\n # iterations and still have good confidence we're covering all the important code paths.\r\n diff_iters=integers(min_value=0, max_value=8)\r\n )\r\n def test_diff(self, array_and_axis, diff_iters: int):\r\n arr, axis = array_and_axis\r\n\r\n # Record some events so when hypothesis reports test statistics we'll be able\r\n # to see roughly which parts of the search space were covered.\r\n event(f'dtype = {np.dtype(arr.dtype).name}')\r\n event(f'ndim = {len(arr.shape)}')\r\n\r\n # If we'll have to clamp the number of differences below for any of the array's axes,\r\n # record that as an event too -- so we'll know if we're running into that too often.\r\n if min(arr.shape) <= diff_iters:\r\n event(\"Clamped diff_iters for at least one axis of the array.\")\r\n\r\n # We've drawn a random integer to use for the number of differencing steps to perform.\r\n # If the length of the current array axis is smaller, clamp it here to avoid an error.\r\n num_diffs = min(arr.shape[axis], diff_iters)\r\n\r\n # TODO parameterize over kwargs; but don't loop here, it'll be too slow.\r\n # Draw the kwargs values (or None) from hypothesis strategies and let it\r\n # decide how to search through the parameter space.\r\n\r\n rt_diff = rt.diff(arr, axis=axis, n=num_diffs) # as of 20200303 defers to numpy (i.e. no riptable-specific implementation)\r\n np_diff = np.diff(arr, axis=axis, n=num_diffs)\r\n assert isinstance(rt_diff, FastArray)\r\n assert_array_equal_(np.array(rt_diff), np_diff)\r\n\r\n @given(examples=generate_sample_test_floats())\r\n def test_double(self, examples):\r\n for i in examples:\r\n rt_double = rt.double(i)\r\n np_double = np.double(i)\r\n assert_equal_(rt_double, np_double)\r\n assert isinstance(rt_double, type(np_double))\r\n\r\n rt_plus = rt_double + 1\r\n np_plus = np_double + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_double - 1\r\n np_minus = np_double - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n rt_square = rt_double ** 2\r\n np_square = np_double ** 2\r\n assert_equal_(rt_square, np_square)\r\n assert isinstance(rt_square, type(np_square))\r\n\r\n rt_sqrt = np.sqrt(rt_double)\r\n np_sqrt = np.sqrt(np_double)\r\n assert_equal_(rt_sqrt, np_sqrt)\r\n isinstance(rt_sqrt, type(np_sqrt))\r\n\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n dtype=ints_floats_datetimes_and_timedeltas(),\r\n order=sampled_from((\"F\", \"C\")),\r\n )\r\n def test_empty(self, shape, dtype, order):\r\n # Empty does not initialize the values in the array, so it cannot be compared to a numpy array element-wise\r\n rt_empty = rt.empty(shape=shape, dtype=dtype, order=order)\r\n assert isinstance(rt_empty, FastArray)\r\n assert_equal_(shape, rt_empty.shape)\r\n assert_equal_(dtype.type, rt_empty.dtype.type)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if len(rt_empty.shape) > 1 and min(rt_empty.shape) > 1:\r\n assert np.isfortran(rt_empty) == (order == \"F\")\r\n else:\r\n assert not np.isfortran(rt_empty)\r\n\r\n # TODO pull the non-subok parts so these are running tests\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6563 riptable does not implement subok\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_datetimes_and_timedeltas()\r\n ),\r\n dtype=ints_floats_or_complex_dtypes(),\r\n order=sampled_from((\"C\", \"F\", \"K\", \"A\")),\r\n subok=booleans(),\r\n )\r\n def test_empty_like(self, arr, dtype, order, subok):\r\n # TODO argument sweep\r\n rt_empty_like = rt.empty_like(arr, dtype=dtype, order=order, subok=subok)\r\n assert_equal_(dtype, rt_empty_like.dtype)\r\n assert_equal_(rt_empty_like.shape, arr.shape)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if (\r\n len(rt_empty_like.shape) > 1\r\n and min(rt_empty_like.shape) > 1\r\n and (order == \"F\" or ((order == \"A\" or order == \"K\") and np.isfortran(arr)))\r\n ):\r\n assert np.isfortran(rt_empty_like)\r\n else:\r\n assert not np.isfortran(rt_empty_like)\r\n\r\n if subok:\r\n assert isinstance(rt_empty_like, FastArray)\r\n else:\r\n assert isinstance(rt_empty_like, np.ndarray)\r\n # FastArray is a subclass of np.ndarray, so also ensure it is not a FastArray\r\n assert not isinstance(rt_empty_like, FastArray)\r\n\r\n @given(examples=generate_sample_test_floats())\r\n def test_float32(self, examples):\r\n for i in examples:\r\n rt_float32 = rt.float32(i)\r\n np_float32 = np.float32(i)\r\n assert_equal_(rt_float32, np_float32)\r\n assert isinstance(rt_float32, type(np_float32))\r\n\r\n rt_plus = rt_float32 + 1\r\n np_plus = np_float32 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_float32 - 1\r\n np_minus = np_float32 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n rt_square = rt_float32 ** 2\r\n np_square = np_float32 ** 2\r\n assert_equal_(rt_square, np_square)\r\n assert isinstance(rt_square, type(np_square))\r\n\r\n rt_sqrt = np.sqrt(rt_float32)\r\n np_sqrt = np.sqrt(np_float32)\r\n assert_equal_(rt_sqrt, np_sqrt)\r\n assert isinstance(rt_sqrt, type(np_sqrt))\r\n\r\n @given(examples=generate_sample_test_floats())\r\n def test_float64(self, examples):\r\n for i in examples:\r\n rt_float64 = rt.float64(i)\r\n np_float64 = np.float64(i)\r\n assert_equal_(rt_float64, np_float64)\r\n assert isinstance(rt_float64, type(np_float64))\r\n\r\n rt_plus = rt_float64 + 1\r\n np_plus = np_float64 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_float64 - 1\r\n np_minus = np_float64 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n rt_square = rt_float64 ** 2\r\n np_square = np_float64 ** 2\r\n assert_equal_(rt_square, np_square)\r\n assert isinstance(rt_square, type(np_square))\r\n\r\n rt_sqrt = np.sqrt(rt_float64)\r\n np_sqrt = np.sqrt(np_float64)\r\n assert_equal_(rt_sqrt, np_sqrt)\r\n assert isinstance(rt_sqrt, type(np_sqrt))\r\n\r\n @pytest.mark.xfail(\r\n reason=\"Related to https://jira/browse/SOQTEST-6478 different endiannesses not handled\"\r\n )\r\n @given(\r\n data=data(),\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(sizes=(32, 64))\r\n ),\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n def test_floor_array(self, data, arr):\r\n # TODO: Modify this to use the 'generate_array_and_where' strategy instead?\r\n where_arr = data.draw(arrays(shape=arr.shape, dtype=boolean_dtypes()))\r\n\r\n # Test #1: Returns new array containing results; no optional parameters provided.\r\n rt_output = rt.floor(arr)\r\n np_output = np.floor(arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #2: Returns new array containing results; 'where' bitmask is provided.\r\n rt_output = rt.floor(arr, where=where_arr)\r\n np_output = np.floor(arr, where=where_arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #3: Results written to array specified in 'out' parameter; no other optional params.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.floor(arr, out=rt_inplace)\r\n np_output = np.floor(arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.floor() did not return a FastArray\")\r\n\r\n # Test #4: Results written to array specified in 'out' parameter; 'where' bitmask is provided.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.floor(arr, where=where_arr, out=rt_inplace)\r\n np_output = np.floor(arr, where=where_arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.floor() did not return a FastArray\")\r\n\r\n @given(scalar=floating_scalar())\r\n def test_floor_scalar(self, scalar):\r\n # test scalars\r\n rt_floor_scalar = rt.floor(scalar)\r\n np_floor_scalar = np.floor(scalar)\r\n assert_equal_(np_floor_scalar, rt_floor_scalar)\r\n\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n fill_value=ints_or_floats_example(),\r\n dtype=ints_or_floats_dtypes(),\r\n order=sampled_from((\"C\", \"F\")),\r\n )\r\n def test_full(self, shape, fill_value, dtype, order):\r\n rt_err_type = np_err_type = rt_full = np_full = None\r\n try:\r\n rt_full = rt.full(shape, fill_value, dtype=dtype, order=order)\r\n except Exception as e:\r\n rt_err_type = type(e)\r\n try:\r\n np_full = np.full(\r\n shape=shape, fill_value=fill_value, dtype=dtype, order=order\r\n )\r\n except Exception as e:\r\n np_err_type = type(e)\r\n\r\n if rt_err_type and np_err_type:\r\n assert rt_err_type == np_err_type\r\n else:\r\n assert_array_equal_(np.array(rt_full), np_full)\r\n assert isinstance(rt_full, FastArray)\r\n assert np.isfortran(rt_full) == np.isfortran(np_full)\r\n\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n fill_value=text(),\r\n order=sampled_from((\"C\", \"F\")),\r\n )\r\n def test_full_str(self, shape, fill_value, order):\r\n rt_full = rt.full(shape, fill_value, order=order)\r\n np_full = np.full(shape, fill_value, order=order)\r\n assert_array_equal_(np.array(rt_full), np_full)\r\n assert isinstance(rt_full, FastArray)\r\n assert np.isfortran(rt_full) == np.isfortran(np_full)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6495 kwargs not implemented in riptable.full()\",\r\n raises=ValueError,\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n fill_value=ints_or_floats_example(),\r\n dtype=ints_or_floats_dtypes(),\r\n order=sampled_from((\"C\", \"F\")),\r\n )\r\n def test_full_kwargs(self, shape, fill_value, dtype, order):\r\n rt_err_type = np_err_type = rt_full = np_full = None\r\n try:\r\n rt_full = rt.full(\r\n shape=shape, fill_value=fill_value, dtype=dtype, order=order\r\n )\r\n except Exception as e:\r\n rt_err_type = type(e)\r\n try:\r\n np_full = np.full(\r\n shape=shape, fill_value=fill_value, dtype=dtype, order=order\r\n )\r\n except Exception as e:\r\n np_err_type = type(e)\r\n\r\n if rt_err_type and np_err_type:\r\n assert rt_err_type == np_err_type\r\n else:\r\n assert_array_equal_(np.array(rt_full), np_full)\r\n assert isinstance(rt_full, FastArray)\r\n assert np.isfortran(rt_full) == np.isfortran(np_full)\r\n\r\n @hypothesis.settings(suppress_health_check=[HealthCheck.too_slow])\r\n @given(tuple_of_arrays=generate_tuples_of_arrays(all_same_height=True))\r\n def test_hstack(self, tuple_of_arrays):\r\n rt_err_type = np_err_type = rt_hstack = np_hstack = None\r\n try:\r\n rt_hstack = rt.hstack(tuple_of_arrays)\r\n except Exception as e:\r\n rt_err_type = type(e)\r\n try:\r\n np_hstack = np.hstack(tuple_of_arrays)\r\n except Exception as e:\r\n np_err_type = type(e)\r\n\r\n if rt_err_type and np_err_type:\r\n assert rt_err_type == np_err_type\r\n else:\r\n assert isinstance(rt_hstack, FastArray)\r\n assert_array_equal_(np.array(rt_hstack), np_hstack)\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=8, signed=True))\r\n def test_int8(self, examples):\r\n for i in examples:\r\n rt_int8 = rt.int8(i)\r\n np_int8 = np.int8(i)\r\n assert_equal_(rt_int8, np_int8)\r\n assert isinstance(rt_int8, type(np_int8))\r\n\r\n rt_plus = rt_int8 + 1\r\n np_plus = np_int8 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_int8 - 1\r\n np_minus = np_int8 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=16, signed=True))\r\n def test_int16(self, examples):\r\n for i in examples:\r\n rt_int16 = rt.int16(i)\r\n np_int16 = np.int16(i)\r\n assert_equal_(rt_int16, np_int16)\r\n assert isinstance(rt_int16, type(np_int16))\r\n\r\n rt_plus = rt_int16 + 1\r\n np_plus = np_int16 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_int16 - 1\r\n np_minus = np_int16 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=32, signed=True))\r\n def test_int32(self, examples):\r\n for i in examples:\r\n rt_err = None\r\n np_err = None\r\n try:\r\n rt_int32 = rt.int32(i)\r\n except BaseException as e:\r\n rt_err = str(e)\r\n try:\r\n np_int32 = np.int32(i)\r\n except BaseException as e:\r\n np_err = str(e)\r\n if rt_err or np_err:\r\n assert rt_err == np_err\r\n else:\r\n assert_equal_(rt_int32, np_int32)\r\n assert isinstance(rt_int32, type(np_int32))\r\n\r\n rt_plus = rt_int32 + 1\r\n np_plus = np_int32 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_int32 - 1\r\n np_minus = np_int32 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=64, signed=True))\r\n def test_int64(self, examples):\r\n for i in examples:\r\n rt_err = None\r\n np_err = None\r\n try:\r\n rt_int64 = rt.int64(i)\r\n except BaseException as e:\r\n rt_err = str(e)\r\n try:\r\n np_int64 = np.int64(i)\r\n except BaseException as e:\r\n np_err = str(e)\r\n\r\n if rt_err or np_err:\r\n assert rt_err == np_err\r\n else:\r\n assert_equal_(rt_int64, np_int64)\r\n assert isinstance(rt_int64, type(np_int64))\r\n\r\n rt_plus = rt_int64 + 1\r\n np_plus = np_int64 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_int64 - 1\r\n np_minus = np_int64 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(arg_dict=interpolation_data())\r\n def test_interp(self, arg_dict):\r\n rt_err = np_err = rt_interp = np_interp = None\r\n\r\n try:\r\n rt_interp = rt.interp(\r\n arg_dict[\"x\"], arg_dict[\"xp\"], arg_dict[\"fp\"]\r\n ) # According to the documentation, Riptable\r\n # does not implement kwargs left, right,\r\n # and period\r\n except Exception as e:\r\n rt_err = e\r\n\r\n try:\r\n np_interp = np.interp(arg_dict[\"x\"], arg_dict[\"xp\"], arg_dict[\"fp\"])\r\n except Exception as e:\r\n np_err = e\r\n\r\n if rt_err or np_err:\r\n assert rt_err == np_err\r\n else:\r\n assert_equal_(rt_interp.dtype.name, np_interp.dtype.name)\r\n assert_allclose(np.array(rt_interp), np_interp)\r\n assert isinstance(rt_interp, FastArray)\r\n\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(endianness=\"=\")\r\n )\r\n )\r\n def test_isfinite(self, arr):\r\n rt_isfinite = rt.isfinite(arr)\r\n np_isfinite = np.isfinite(arr)\r\n assert_array_equal_(rt_isfinite, np_isfinite)\r\n assert isinstance(rt_isfinite, FastArray)\r\n\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(endianness=\"=\")\r\n )\r\n )\r\n def test_isinf(self, arr):\r\n rt_isinf = rt.isinf(arr)\r\n np_isinf = np.isinf(arr)\r\n assert_array_equal_(rt_isinf, np_isinf)\r\n assert isinstance(rt_isinf, FastArray)\r\n\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(endianness=\"=\")\r\n )\r\n )\r\n def test_isnan(self, arr):\r\n rt_isnan = rt.isnan(arr)\r\n np_isnan = np.isnan(arr)\r\n assert_array_equal_(rt_isnan, np_isnan)\r\n assert isinstance(rt_isnan, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-339: lexsort broken for ndarray and FastArray input types\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Performance issues when running on TeamCity\"\r\n )\r\n @given(data())\r\n def test_lexsort_basic(self, data):\r\n shape, dtype = (\r\n shared(ndarray_shape_strategy(max_rank=1)),\r\n shared(ints_floats_datetimes_and_timedeltas()),\r\n )\r\n a = data.draw(arrays(shape=shape, dtype=dtype))\r\n b = data.draw(arrays(shape=shape, dtype=dtype))\r\n\r\n assert_array_equal_(np.lexsort((b, a)), rt.lexsort((list(b), list(a))))\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-339: lexsort broken for ndarray and FastArray input types\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Performance issues when running on TeamCity\"\r\n )\r\n @given(data())\r\n def test_lexsort_basic_fail(self, data):\r\n shape, dtype = (\r\n shared(ndarray_shape_strategy(max_rank=1)),\r\n shared(ints_or_floats_dtypes()),\r\n )\r\n a = data.draw(arrays(shape=shape, dtype=dtype))\r\n b = data.draw(arrays(shape=shape, dtype=dtype))\r\n\r\n rt_lexsort_args = [(FA(b), FA(a)), (FA(b), a), (b, FA(a)), (b, a)]\r\n for rt_arg in rt_lexsort_args:\r\n assert_array_equal_(np.lexsort((b, a)), rt.lexsort(rt_arg))\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-339: lexsort broken for ndarray and FastArray input types\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Performance issues when running on TeamCity\"\r\n )\r\n @given(data())\r\n def test_lexsort_mixed(self, data):\r\n shape, dtype = (\r\n shared(ndarray_shape_strategy(max_rank=1)),\r\n ints_floats_datetimes_and_timedeltas(),\r\n )\r\n a = data.draw(arrays(shape=shape, dtype=dtype))\r\n b = data.draw(arrays(shape=shape, dtype=dtype))\r\n\r\n assert_array_equal_(np.lexsort((b, a)), rt.lexsort((list(b), list(a))))\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-339: lexsort broken for ndarray and FastArray input types\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Performance issues when running on TeamCity\"\r\n )\r\n @given(data())\r\n def test_lexsort_mixed_fail(self, data):\r\n shape, dtype = (\r\n shared(ndarray_shape_strategy(max_rank=1)),\r\n ints_floats_datetimes_and_timedeltas(),\r\n )\r\n a = data.draw(arrays(shape=shape, dtype=dtype))\r\n b = data.draw(arrays(shape=shape, dtype=dtype))\r\n\r\n rt_lexsort_args = [(FA(b), FA(a)), (FA(b), a), (b, FA(a)), (b, a)]\r\n for rt_arg in rt_lexsort_args:\r\n assert_array_equal_(np.lexsort((b, a)), rt.lexsort(rt_arg))\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-339: lexsort broken for ndarray and FastArray input types\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Performance issues when running on TeamCity\"\r\n )\r\n @given(data())\r\n def test_lexsort_many_columns(self, data):\r\n k = data.draw(integers(min_value=1, max_value=_MAX_SHAPE_SIZE // 10))\r\n shape, dtype = (\r\n shared(ndarray_shape_strategy(max_rank=1)),\r\n shared(integer_dtypes(endianness=\"=\")),\r\n )\r\n\r\n keys: List[List[int]] = list()\r\n for _ in range(k):\r\n keys.append(list(data.draw(arrays(shape=shape, dtype=dtype))))\r\n\r\n assert_array_equal_(np.lexsort(keys), rt.lexsort(keys))\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-339: lexsort broken for ndarray and FastArray input types\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Performance issues when running on TeamCity\"\r\n )\r\n @given(data())\r\n def test_lexsort_many_columns_fail(self, data):\r\n k = data.draw(integers(min_value=1, max_value=_MAX_SHAPE_SIZE // 10))\r\n shape, dtype = (\r\n shared(ndarray_shape_strategy(max_rank=1)),\r\n shared(integer_dtypes(endianness=\"=\")),\r\n )\r\n\r\n keys: List[FastArray] = list()\r\n for _ in range(k):\r\n keys.append(FA(data.draw(arrays(shape=shape, dtype=dtype))))\r\n\r\n assert_array_equal_(np.lexsort(keys), rt.lexsort(keys))\r\n\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(endianness=\"=\")\r\n )\r\n )\r\n def test_log_array(self, arr):\r\n rt_log = rt.log(arr)\r\n np_log = np.log(arr)\r\n assert_allclose(np.array(rt_log), np_log, rtol=1e-6)\r\n assert isinstance(rt_log, FastArray)\r\n\r\n @given(scalar=floats())\r\n def test_log_scalar(self, scalar):\r\n rt_log = rt.log(scalar)\r\n np_log = np.log(scalar)\r\n assert_allclose(rt_log, np_log, rtol=1e-6)\r\n\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(endianness=\"=\")\r\n )\r\n )\r\n def test_log10_array(self, arr):\r\n rt_log10 = rt.log10(arr)\r\n np_log10 = np.log10(arr)\r\n assert_allclose(np.array(rt_log10), np_log10, rtol=1e-6)\r\n assert isinstance(rt_log10, FastArray)\r\n\r\n @given(scalar=floats())\r\n def test_log10_scalar(self, scalar):\r\n rt_log10 = rt.log10(scalar)\r\n np_log10 = np.log10(scalar)\r\n assert_allclose(rt_log10, np_log10, rtol=1e-6)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"This test exposes a known bug around NaN-handling in 'max' that needs to be fixed.\"\r\n )\r\n @given(\r\n arr_axis_tuple=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_datetimes_and_timedeltas()\r\n )\r\n )\r\n @given(mats=same_structure_ndarrays())\r\n def test_maximum(self, mats):\r\n mat1, mat2 = mats\r\n\r\n np_output = np.maximum(mat1, mat2)\r\n rt_output = rt.maximum(mat1, mat2)\r\n\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # TODO: Enable this assertion once we've fixed riptable so rt.maximum returns a FastArray.\r\n # assert isinstance(rt_output, FastArray)\r\n\r\n @given(\r\n arr_axis_tuple=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_datetimes_and_timedeltas()\r\n )\r\n )\r\n def test_min(self, arr_axis_tuple):\r\n arr, axis = arr_axis_tuple\r\n\r\n rt_output = rt.min(arr, axis=axis)\r\n np_output = np.min(arr, axis=axis)\r\n\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # TODO: Enable this assertion once we've fixed riptable so rt.maximum returns a FastArray.\r\n # if axis: #if axis is None, it will return a scalar\r\n # assert isinstance(rt_output, FastArray)\r\n\r\n @pytest.mark.parametrize(\r\n \"func\",\r\n [\r\n # TODO add params: nanmean, nansum, nanstd, nanvar, nanargmin, nanargmax\r\n # TODO add other missing array methods, then dynamically generate these functions from introspection of numpy and riptable\r\n # List of ndarray array methods: https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#array-methods\r\n \"abs\",\r\n \"all\",\r\n \"any\",\r\n \"argmax\",\r\n \"argmin\",\r\n \"argsort\",\r\n # TODO add cumprod\r\n \"cumsum\",\r\n \"mean\",\r\n \"median\",\r\n \"nanmedian\",\r\n \"percentile\",\r\n \"std\",\r\n \"var\",\r\n pytest.param(\r\n \"sum\",\r\n marks=[\r\n pytest.mark.xfail(\r\n reason=\"Need to investigate intermittent failures possibly due to roundoff errors.\"\r\n )\r\n ],\r\n ),\r\n pytest.param(\r\n \"nanmax\",\r\n marks=[\r\n pytest.mark.xfail(\r\n reason=\"RIP-417: This test exposes a known bug around NaN-handling in 'nanmax' that needs to be fixed.\"\r\n )\r\n ],\r\n ),\r\n pytest.param(\r\n \"nanmin\",\r\n marks=[\r\n pytest.mark.xfail(\r\n reason=\"RIP-417: This test exposes a known bug around NaN-handling in 'nanmin' that needs to be fixed.\"\r\n )\r\n ],\r\n ),\r\n pytest.param(\r\n \"max\",\r\n marks=[\r\n pytest.mark.xfail(\r\n reason=\"Conflict in comparing FastArray with invalids that don't exist as ndarray invalids. Need to handle invalid assertion checks.\"\r\n )\r\n ],\r\n ),\r\n pytest.param(\r\n \"nanpercentile\",\r\n marks=[\r\n pytest.mark.xfail(\r\n reason=\"Investigate frequent TeamCity hypothesis DeadlineExceeded exceptions that never occur on local runs\"\r\n )\r\n ],\r\n ),\r\n ],\r\n )\r\n @pytest.mark.parametrize(\r\n \"include_invalid\",\r\n [\r\n False\r\n ], # TODO enable including invalids and use masked arrays to check valid and possibly invalid values\r\n )\r\n def test_array_methods(self, func, include_invalid):\r\n # TODO rework so the generated array and axis can be cached and reused, otherwise most of the time spent for this test is generating arrays and an axis\r\n # Attempted to use the hypothesis cacheable decorator, but it doesn't cache the strategy for reuse\r\n # Investigate reworking generate_array_and_axis by using the defines_strategy_with_reusable_values decorator\r\n @given(\r\n arr_axis_tuple=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(),\r\n dtype=ints_or_floats_dtypes(),\r\n include_invalid=include_invalid,\r\n )\r\n )\r\n def inner(arr_axis_tuple):\r\n arr, axis = arr_axis_tuple\r\n\r\n # TODO enable this assertion for guarded funcs once we've fixed riptable so these return a fastarray.\r\n def _check_fastarray(inst):\r\n if (\r\n axis\r\n ): # need an axis to check if output is a FastArray, otherwise output is a scalar\r\n assert isinstance(inst, rt.FastArray)\r\n\r\n args = (func, arr)\r\n kwargs = {}\r\n if func not in [\"abs\"]:\r\n kwargs[\"axis\"] = axis\r\n # set up keyword arguments needed for some of the rt_numpy functions\r\n if \"std\" in func or \"var\" in func:\r\n kwargs[\"ddof\"] = 1\r\n if \"percentile\" in func:\r\n kwargs[\"interpolation\"] = \"linear\"\r\n kwargs[\"q\"] = 50\r\n if \"argsort\" == func:\r\n kwargs[\"kind\"] = \"stable\"\r\n\r\n # Test #1: Check calling .func() as a module function in numpy vs. riptable.\r\n rt_output = operator.methodcaller(*args, **kwargs)(rt)\r\n np_output = operator.methodcaller(*args, **kwargs)(np)\r\n assert_array_equal_(rt_output, np_output)\r\n\r\n # Test #2: Check calling .func() as a module function in numpy vs. riptable.\r\n # This time, explicitly wrap the ndarray generated by hypothesis in a FastArray\r\n # so we're sure to get the FastArray implementation.\r\n f_arr = rt.FA(arr)\r\n args = (func, f_arr)\r\n rt_output = operator.methodcaller(*args, **kwargs)(rt)\r\n np_output = operator.methodcaller(*args, **kwargs)(np)\r\n assert_array_equal_(rt_output, np_output)\r\n # _check_fastarray(rt_output) # rt_output should be a FastArray, but is a ndarray\r\n\r\n # Test #3: Call the .func() method on both the FastArray and the ndarray.\r\n # Either FastArray or ndarray does not support the guarded member names.\r\n common_members, _ = _NDARRAY_FASTARRAY_COMMON_AND_DIFF\r\n if func in common_members:\r\n rt_output = operator.methodcaller(func, **kwargs)(f_arr)\r\n np_output = operator.methodcaller(func, **kwargs)(arr)\r\n assert_array_equal_(rt_output, np_output)\r\n # _check_fastarray(rt_output) # rt_output should be a FastArray, but is a ndarray\r\n\r\n inner()\r\n\r\n @given(mats=same_structure_ndarrays())\r\n def test_minimum(self, mats):\r\n mat1, mat2 = mats\r\n\r\n np_output = np.minimum(mat1, mat2)\r\n rt_output = rt.minimum(mat1, mat2)\r\n\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # TODO: Enable this assertion once we've fixed riptable so rt.minimum returns a FastArray.\r\n # assert isinstance(rt_output, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6497 Riptable.nan_to_num() does not return a FastArray\",\r\n raises=AssertionError,\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(array=arrays(shape=ndarray_shape_strategy(), dtype=floating_dtypes()))\r\n def test_nan_to_num_array(self, array):\r\n rt_nan_to_num = rt.nan_to_num(array)\r\n np_nan_to_num = np.nan_to_num(array)\r\n\r\n assert_allclose(rt_nan_to_num, np_nan_to_num)\r\n assert isinstance(rt_nan_to_num, FastArray)\r\n\r\n @given(scalar=floats())\r\n def test_nan_to_num_scalar(self, scalar):\r\n rt_nan_to_num = rt.nan_to_num(scalar)\r\n np_nan_to_num = np.nan_to_num(scalar)\r\n\r\n assert_allclose(rt_nan_to_num, np_nan_to_num)\r\n\r\n @given(\r\n arr=arrays(shape=ndarray_shape_strategy(), dtype=floating_dtypes()),\r\n q=floats(min_value=0, max_value=100),\r\n )\r\n def test_nanpercentile_single(self, arr, q):\r\n interpolations = [\"linear\", \"lower\", \"higher\", \"midpoint\", \"nearest\"]\r\n for interpolation in interpolations:\r\n # todo - rt_nanpercentile should come from riptable\r\n rt_nanpercentile = np.nanpercentile(arr, q=q, interpolation=interpolation)\r\n np_nanpercentile = np.nanpercentile(arr, q=q, interpolation=interpolation)\r\n assert_allclose(rt_nanpercentile, np_nanpercentile)\r\n\r\n # @given(arr=arrays(shape=ndarray_shape_strategy(), dtype=floating_dtypes()), q=floats(min_value=0, max_value=100))\r\n # def test_nanpercentile_single(self, arr, q):\r\n # interpolations = ['linear', 'lower', 'higher', 'midpoint', 'nearest']\r\n # for interpolation in interpolations:\r\n # # todo - rt_nanpercentile should come from riptable\r\n # rt_nanpercentile = np.nanpercentile(arr, q=q, interpolation=interpolation)\r\n # np_nanpercentile = np.nanpercentile(arr, q=q, interpolation=interpolation)\r\n # assert_allclose(rt_nanpercentile, np_nanpercentile)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6497 Riptable.nanpercentile() does not return a FastArray\",\r\n raises=AssertionError,\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(shape=ndarray_shape_strategy(), dtype=floating_dtypes()),\r\n q=lists(\r\n floats(min_value=0, max_value=100), min_size=10, max_size=50, unique=True\r\n ),\r\n )\r\n def test_nanpercentile_array(self, arr, q):\r\n interpolations = [\"linear\", \"lower\", \"higher\", \"midpoint\", \"nearest\"]\r\n for interpolation in interpolations:\r\n # todo - rt_nanpercentile should come from riptable\r\n rt_output = np.nanpercentile(arr, q=q, interpolation=interpolation)\r\n np_output = np.nanpercentile(arr, q=q, interpolation=interpolation)\r\n\r\n assert_allclose(rt_output, np_output)\r\n if len(arr.shape) > 1:\r\n assert isinstance(rt_output, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=(\r\n \"https://jira/browse/SOQTEST-6637 Riptable does not convert the array to a FastArray, so it does not guarantee nanstd will be an available attribute\\n\"\r\n \"https://jira/browse/SOQTEST-6497 Riptable.nanstd() does not return a FastArray\"\r\n ),\r\n raises=(AttributeError, AssertionError),\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(arr_axis_and_ddof=generate_array_axis_and_ddof())\r\n def test_nanstd(self, arr_axis_and_ddof):\r\n \"\"\"\r\n This function has a different default behavior from numpy. Riptable, like pandas, has a default ddof of 1, while\r\n numpy uses 0.\r\n \"\"\"\r\n arr = arr_axis_and_ddof[\"arr\"]\r\n axis = arr_axis_and_ddof[\"axis\"]\r\n ddof = arr_axis_and_ddof[\"ddof\"]\r\n\r\n rt_output = rt.nanstd(arr, axis=axis, ddof=ddof)\r\n np_output = np.nanstd(arr, axis=axis, ddof=ddof)\r\n\r\n assert_allclose(rt_output, np_output)\r\n if axis and len(arr.shape) > 1:\r\n assert isinstance(rt_output, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=(\r\n \"https://jira/browse/SOQTEST-6637 Riptable does not convert the array to a FastArray, so it does not guarantee nansum will be an available attribute\\n\",\r\n \"nansum does not implement the axis argument either\",\r\n )\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n array_and_axis=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(max_rank=1), dtype=ints_or_floats_dtypes()\r\n )\r\n )\r\n def test_nansum(self, array_and_axis):\r\n \"\"\"\r\n riptable.nansum() does not yet implement the axis argument, since riptable is mostly focused on 1D FastArrays.\r\n test_nansum_1D only selects arrays that are rank 0 or 1. Riptable's nansum, like nanmean, does not cast the array\r\n passed in to a FastArray--when a FastArray is not passed in an Attribute exception occurs because the function\r\n tries calling array.nansum().\r\n \"\"\"\r\n arr, axis = array_and_axis\r\n arr = FastArray(arr)\r\n\r\n rt_output = rt.nansum(arr, axis=axis)\r\n np_output = np.nansum(arr, axis=axis)\r\n\r\n assert_allclose(rt_output, np_output)\r\n if axis:\r\n assert isinstance(rt_output, FastArray)\r\n\r\n # The floats should have the same byte-order as the machine at the moment (https://jira/browse/SOQTEST-6478) -> endianness=\"=\"\r\n # and riptable only officially supports float32 and float64 floating-point datatypes, so using other ones occasionally\r\n # leads to errors.\r\n # Split up ints and floats to ensure the same datatypes for widening. (int->int64, float->float64)\r\n @pytest.mark.skip(\r\n reason=\"When the array has very large numbers and numbers closed to zero, numpy and riptable can produce different results.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(max_rank=1),\r\n dtype=floating_dtypes(endianness=\"=\", sizes=(32, 64)),\r\n )\r\n )\r\n def test_nansum_1D_float(self, arr):\r\n arr = FastArray(arr)\r\n # TODO: numpy is not widening the output array as expected to 64 bits all the time, so it is being forced here.\r\n rt_output = rt.nansum(arr, axis=None, dtype=np.float64)\r\n np_output = np.nansum(arr, axis=None, dtype=np.float64)\r\n assert_allclose(rt_output, np_output)\r\n\r\n # The floats should have the same byte-order as the machine at the moment (https://jira/browse/SOQTEST-6478) -> endianness=\"=\"\r\n # Split up ints and floats to ensure the same datatypes for widening. (int->int64, float->float64)\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6670 Nansum does not follow the dtype argument and returns a float64\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(max_rank=1),\r\n dtype=integer_dtypes(endianness=\"=\"),\r\n )\r\n )\r\n def test_nansum_1D_int(self, arr):\r\n arr = FastArray(arr)\r\n # TODO: numpy is not widening the output array as expected to 64 bits all the time, so it is being forced here.\r\n rt_output = rt.nansum(arr, axis=None, dtype=np.int64)\r\n np_output = np.nansum(arr, axis=None, dtype=np.int64)\r\n assert rt_output.dtype.type == np.int64\r\n assert_allclose(rt_output, np_output)\r\n\r\n @pytest.mark.xfail(\r\n reason=(\r\n \"https://jira/browse/SOQTEST-6637 Riptable does not convert the array to a FastArray, so it does not guarantee nanvar will be an available attribute\\n\"\r\n \"https://jira/browse/SOQTEST-6497 Riptable.nanvar() does not return a FastArray\"\r\n ),\r\n raises=(AttributeError, AssertionError),\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(arr_axis_and_ddof=generate_array_axis_and_ddof())\r\n def test_nanvar(self, arr_axis_and_ddof):\r\n arr = arr_axis_and_ddof[\"arr\"]\r\n axis = arr_axis_and_ddof[\"axis\"]\r\n ddof = arr_axis_and_ddof[\"ddof\"]\r\n\r\n rt_output = rt.nanvar(arr, axis=axis, ddof=ddof)\r\n np_output = np.nanvar(arr, axis=axis, ddof=ddof)\r\n\r\n assert_allclose(rt_output, np_output)\r\n if axis and len(arr.shape) > 1:\r\n assert isinstance(rt_output, FastArray)\r\n\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n dtype=ints_or_floats_dtypes(),\r\n order=sampled_from((\"F\", \"C\")),\r\n )\r\n def test_ones(self, shape, dtype, order):\r\n rt_ones = rt.ones(shape, dtype, order)\r\n np_ones = np.ones(shape=shape, dtype=dtype, order=order)\r\n assert isinstance(rt_ones, FastArray)\r\n\r\n assert_equal_(shape, rt_ones.shape)\r\n assert_equal_(dtype.type, rt_ones.dtype.type)\r\n assert_array_equal_(rt_ones, np_ones)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if len(rt_ones.shape) > 1 and min(rt_ones.shape) > 1:\r\n assert np.isfortran(rt_ones) == (order == \"F\")\r\n else:\r\n assert not np.isfortran(rt_ones)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6495 kwargs not implemented in riptable.ones\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n dtype=ints_or_floats_dtypes(),\r\n order=sampled_from((\"F\", \"C\")),\r\n )\r\n def test_ones_kwargs(self, shape, dtype, order):\r\n rt_ones = rt.ones(shape=shape, dtype=dtype, order=order)\r\n np_ones = np.ones(shape=shape, dtype=dtype, order=order)\r\n assert isinstance(rt_ones, FastArray)\r\n\r\n assert_equal_(shape, rt_ones.shape)\r\n assert_equal_(dtype.type, rt_ones.dtype.type)\r\n assert_array_equal_(rt_ones, np_ones)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if len(rt_ones.shape) > 1 and min(rt_ones.shape) > 1:\r\n assert np.isfortran(rt_ones) == (order == \"F\")\r\n else:\r\n assert not np.isfortran(rt_ones)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6563 riptable does not implement subok\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_datetimes_and_timedeltas()\r\n ),\r\n dtype=ints_floats_or_complex_dtypes(),\r\n order=sampled_from((\"C\", \"F\", \"K\", \"A\")),\r\n subok=booleans(),\r\n )\r\n def test_ones_like(self, arr, dtype, order, subok):\r\n rt_ones_like = rt.ones_like(arr, dtype=dtype, order=order, subok=subok)\r\n np_ones_like = np.ones_like(arr, dtype=dtype, order=order, subok=subok)\r\n\r\n assert_equal_(dtype, rt_ones_like.dtype)\r\n assert_equal_(rt_ones_like.shape, arr.shape)\r\n assert_array_equal_(rt_ones_like, np_ones_like)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if (\r\n len(rt_ones_like.shape) > 1\r\n and min(rt_ones_like.shape) > 1\r\n and (order == \"F\" or ((order == \"A\" or order == \"K\") and np.isfortran(arr)))\r\n ):\r\n assert np.isfortran(rt_ones_like)\r\n else:\r\n assert not np.isfortran(rt_ones_like)\r\n\r\n if subok:\r\n assert isinstance(rt_ones_like, FastArray)\r\n else:\r\n assert isinstance(rt_ones_like, np.ndarray)\r\n # FastArray is a subclass of np.ndarray, so also ensure it is not a FastArray\r\n assert not isinstance(rt_ones_like, FastArray)\r\n\r\n @given(\r\n arr=arrays(shape=ndarray_shape_strategy(), dtype=floating_dtypes()),\r\n q=floats(min_value=0, max_value=100),\r\n )\r\n def test_percentile_single(self, arr, q):\r\n interpolations = [\"linear\", \"lower\", \"higher\", \"midpoint\", \"nearest\"]\r\n for interpolation in interpolations:\r\n # todo - rt_percentile should come from riptable\r\n rt_output = np.percentile(arr, q=q, interpolation=interpolation, axis=None)\r\n np_output = np.percentile(arr, q=q, interpolation=interpolation, axis=None)\r\n assert_allclose(rt_output, np_output)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6497 Riptable.percentile() does not return a FastArray\",\r\n raises=AssertionError,\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n array_and_axis=generate_array_and_axis(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes()\r\n ),\r\n q=lists(\r\n floats(min_value=0, max_value=100), min_size=10, max_size=50, unique=True\r\n ),\r\n )\r\n def test_percentile_array(self, array_and_axis, q):\r\n arr, axis = array_and_axis\r\n interpolations = [\"linear\", \"lower\", \"higher\", \"midpoint\", \"nearest\"]\r\n for interpolation in interpolations:\r\n rt_output = rt.percentile(arr, q=q, interpolation=interpolation, axis=axis)\r\n np_output = np.percentile(arr, q=q, interpolation=interpolation, axis=axis)\r\n assert_allclose(rt_output, np_output)\r\n if axis and len(arr.shape) > 1:\r\n assert isinstance(rt_output, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6497 Riptable.putmask does not cast input to a FastArray\",\r\n raises=AssertionError,\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n array_and_mask=generate_array_and_where(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(endianness=\"=\")\r\n ),\r\n rep_val=floats(),\r\n )\r\n def test_putmask(self, array_and_mask, rep_val):\r\n arr, mask = array_and_mask\r\n rt_err = None\r\n rt_putmask = arr.copy()\r\n np_err = None\r\n np_putmask = arr.copy()\r\n try:\r\n rt.putmask(rt_putmask, mask, rep_val)\r\n except OverflowError:\r\n rt_err = OverflowError\r\n\r\n try:\r\n np.putmask(np_putmask, mask, rep_val)\r\n except OverflowError:\r\n np_err = OverflowError\r\n\r\n if rt_err or np_err:\r\n assert rt_err == np_err\r\n else:\r\n assert_allclose(rt_putmask, np_putmask)\r\n assert isinstance(rt_putmask, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-341: quantile's _get_score raises an index error when getting the view from _val and using it to access the ndarray.\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=one_darray_shape_strategy(), dtype=floating_dtypes(sizes=(32, 64))\r\n )\r\n )\r\n def test_quantile(self, arr):\r\n # For a one to one equivalence of supported interpolation methods between numpy and riptable:\r\n # 1) np.quantile would need to support riptable's fraction method\r\n # 2) rt.quantile would need to support numpy's linear, midpoint, and nearest methods\r\n # Numpy quantile reference https://docs.scipy.org/doc/numpy/reference/generated/numpy.quantile.html\r\n # Tracked in Jira https://jira/browse/RIP-344\r\n interpolations = [\"lower\", \"higher\"]\r\n for interpolation in interpolations:\r\n q = random.random()\r\n rt_quantile, _, _ = rt.quantile(arr, q, interpolation)\r\n np_quantile = np.quantile(arr, q, interpolation=interpolation)\r\n assert_allclose(\r\n rt_quantile, np_quantile, err_msg=f\"to reproduce use quantile {q}\"\r\n )\r\n\r\n @given(\r\n arr=arrays(shape=ndarray_shape_strategy(), dtype=ints_or_floats_dtypes()),\r\n rep=integers(min_value=0, max_value=10),\r\n axis=sampled_from((None, 0, 1)),\r\n )\r\n def test_repeat_integer_repeats(self, arr, rep, axis):\r\n if axis == 1 and len(arr.shape) == 1:\r\n axis = 0\r\n\r\n rt_repeat = rt.repeat(arr, repeats=rep, axis=axis)\r\n np_repeat = np.repeat(arr, repeats=rep, axis=axis)\r\n assert_allclose(np.array(rt_repeat), np_repeat)\r\n\r\n @given(\r\n arr_axis_and_rep=generate_array_axis_and_repeats_array(\r\n dtype=ints_or_floats_dtypes(), shape=ndarray_shape_strategy()\r\n )\r\n )\r\n def test_repeat_array_repeats(self, arr_axis_and_rep):\r\n arr, axis, rep = arr_axis_and_rep\r\n\r\n rt_repeat = rt.repeat(arr, repeats=rep, axis=axis)\r\n np_repeat = np.repeat(arr, repeats=rep, axis=axis)\r\n\r\n assert_allclose(np.array(rt_repeat), np_repeat)\r\n assert isinstance(rt_repeat, FastArray)\r\n\r\n @given(\r\n arr_and_dim=generate_reshape_array_and_shape_strategy(\r\n shape=ndarray_shape_strategy(), dtype=ints_or_floats_dtypes()\r\n )\r\n )\r\n def test_reshape(self, arr_and_dim):\r\n arr, dim = arr_and_dim\r\n orders = [\"C\", \"F\", \"A\"]\r\n for order in orders:\r\n rt_reshape = rt.reshape(arr, dim, order=order)\r\n np_reshape = np.reshape(arr, dim, order=order)\r\n assert_allclose(np.array(rt_reshape), np_reshape)\r\n assert np.isfortran(rt_reshape) == np.isfortran(np_reshape)\r\n assert isinstance(rt_reshape, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6530 riptable.round() does not return FastArray and decimals arg not yet implemented\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(sizes=(32, 64))\r\n )\r\n )\r\n def test_round_array(self, arr):\r\n # TODO: Use range of decimals once https://jira/browse/SOQTEST-6530 is addressed\r\n decimals = [0]\r\n # decimals = range(-5, 100)\r\n\r\n for decimal in decimals:\r\n # test array\r\n rt_output = rt.round(arr, decimals=decimal)\r\n np_output = np.round(arr, decimals=decimal)\r\n\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n assert isinstance(rt_output, FastArray)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6530 should fail on +/-inf, and [-0.5,-0], since riptable.round calls builtin round. Decimals arg also not yet implemented\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(scalar=floating_scalar())\r\n def test_round_scalar(self, scalar):\r\n # TODO: Use range of decimals once https://jira/browse/SOQTEST-6530 is addressed\r\n decimals = [0]\r\n # decimals = range(-5, 100)\r\n for decimal in decimals:\r\n # test scalars\r\n rt_round_scalar = rt.round(scalar, decimals=decimal)\r\n np_round_scalar = np.round(scalar, decimals=decimal)\r\n assert_equal_(\r\n rt_round_scalar,\r\n np_round_scalar,\r\n err_msg=f\"Rounding error on {type(scalar)} {scalar}\",\r\n )\r\n\r\n @pytest.mark.xfail(reason=\"RIP-345 - discrepancy between inserts position points\")\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(arrays(shape=one_darray_shape_strategy(), dtype=integer_dtypes()))\r\n def test_searchsorted(self, arr):\r\n sides = {\"left\", \"right\"}\r\n\r\n arr.sort()\r\n v = arr[arr % 2 == 0]\r\n\r\n for side in sides:\r\n rt_indicies = rt.searchsorted(arr, v, side)\r\n np_indicies = np.searchsorted(arr, v, side)\r\n assert_array_equal_(\r\n rt_indicies,\r\n np_indicies,\r\n err_msg=f\"using array {arr}\\nvalues to insert {v}\\nside {side}\",\r\n )\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-350 - see Python/core/riptable/tests/test_base_function.TestStd.test_std for a materialized counterexample\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=one_darray_shape_strategy(max_shape_size=10),\r\n # do not consider overflow; numpy and riptable differ in how they behave on overflow\r\n elements=integers(-int(_MAX_INT / 10), int(_MAX_INT / 10)),\r\n dtype=integer_dtypes(endianness=\"=\", sizes=(64,)),\r\n )\r\n )\r\n def test_std(self, arr):\r\n np_std = np.std(arr, ddof=1)\r\n rt_std = rt.std(rt.FastArray(arr))\r\n assert_equal_(rt_std, np_std, decimal=6)\r\n\r\n @given(\r\n arr=arrays(\r\n shape=one_darray_shape_strategy(max_shape_size=10),\r\n # do not consider overflow; numpy and riptable differ in how they behave on overflow\r\n elements=integers(-int(_MAX_INT / 10), int(_MAX_INT / 10)),\r\n dtype=integer_dtypes(endianness=\"=\", sizes=(64,)),\r\n )\r\n )\r\n def test_sum_int(self, arr):\r\n np_sum = np.sum(arr)\r\n rt_sum = rt.sum(rt.FastArray(arr))\r\n assert_equal_(int(rt_sum), int(np_sum))\r\n\r\n @pytest.mark.xfail(\r\n reason=\"RIP-351 - see Python/core/riptable/tests/test_base_function.TestSum.test_sum_float for a materialized counterexample\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=one_darray_shape_strategy(max_shape_size=10),\r\n # do not consider overflow; numpy and riptable differ in how they behave on overflow\r\n elements=floats(-int(_MAX_FLOAT / 10), int(_MAX_FLOAT / 10)),\r\n dtype=floating_dtypes(endianness=\"=\", sizes=(64,)),\r\n )\r\n )\r\n def test_sum_float(self, arr):\r\n np_sum = np.sum(arr)\r\n rt_sum = rt.sum(rt.FastArray(arr))\r\n assert_equal_(rt_sum, np_sum, decimal=6)\r\n\r\n @pytest.mark.skip(reason=\"Resolve DeadlineExceeded errors on workflow runs\")\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(max_shape_size=5),\r\n dtype=floating_dtypes(endianness=\"=\", sizes=(32, 64)),\r\n ),\r\n shape=ndarray_shape_strategy(),\r\n )\r\n def test_tile(self, arr, shape):\r\n np_result = np.tile(arr, shape)\r\n rt_result = rt.tile(arr, shape)\r\n assert_array_equal_(rt_result, np_result)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/RIP-358 discrepency between rt.trunc and np.trunc\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n data=data(),\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=floating_dtypes(sizes=(32, 64))\r\n ),\r\n )\r\n def test_trunc(self, data, arr):\r\n # TODO: Modify this to use the 'generate_array_and_where' strategy instead?\r\n where_arr = data.draw(arrays(shape=arr.shape, dtype=boolean_dtypes()))\r\n\r\n # Test #1: Returns new array containing results; no optional parameters provided.\r\n rt_output = rt.trunc(arr)\r\n np_output = np.trunc(arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #2: Returns new array containing results; 'where' bitmask is provided.\r\n rt_output = rt.trunc(arr, where=where_arr)\r\n np_output = np.trunc(arr, where=where_arr)\r\n assert isinstance(rt_output, FastArray)\r\n assert_array_equal_(np.array(rt_output), np_output)\r\n\r\n # Test #3: Results written to array specified in 'out' parameter; no other optional params.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.trunc(arr, out=rt_inplace)\r\n np_output = np.trunc(arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.trunc() did not return a FastArray\")\r\n\r\n # Test #4: Results written to array specified in 'out' parameter; 'where' bitmask is provided.\r\n rt_inplace = np.zeros_like(arr)\r\n np_inplace = np.zeros_like(arr)\r\n rt_output = rt.trunc(arr, where=where_arr, out=rt_inplace)\r\n np_output = np.trunc(arr, where=where_arr, out=np_inplace)\r\n assert_array_equal_(np.array(rt_inplace), np_inplace)\r\n # TODO: Add assertions for rt_output and np_output -- what are they expected to return when the 'out' parameter is specified?\r\n # assert isinstance(rt_output, FastArray, msg=\"riptable.trunc() did not return a FastArray\")\r\n\r\n @given(scalar=floating_scalar())\r\n def test_trunc_scalar(self, scalar):\r\n # test scalars\r\n rt_trunc_scalar = rt.trunc(scalar)\r\n np_trunc_scalar = np.trunc(scalar)\r\n assert_equal_(rt_trunc_scalar, np_trunc_scalar)\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=8, signed=False))\r\n def test_uint8(self, examples):\r\n for i in examples:\r\n rt_uint8 = rt.uint8(i)\r\n np_uint8 = np.uint8(i)\r\n assert_equal_(rt_uint8, np_uint8)\r\n assert isinstance(rt_uint8, type(np_uint8))\r\n\r\n rt_plus = rt_uint8 + 1\r\n np_plus = np_uint8 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_uint8 - 1\r\n np_minus = np_uint8 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=16, signed=False))\r\n def test_uint16(self, examples):\r\n for i in examples:\r\n rt_uint16 = rt.uint16(i)\r\n np_uint16 = np.uint16(i)\r\n assert_equal_(rt_uint16, np_uint16)\r\n assert isinstance(rt_uint16, type(np_uint16))\r\n\r\n rt_plus = rt_uint16 + 1\r\n np_plus = np_uint16 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_uint16 - 1\r\n np_minus = np_uint16 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=32, signed=False))\r\n def test_uint32(self, examples):\r\n for i in examples:\r\n rt_uint32 = rt.uint32(i)\r\n np_uint32 = np.uint32(i)\r\n assert_equal_(rt_uint32, np_uint32)\r\n assert isinstance(rt_uint32, type(np_uint32))\r\n\r\n rt_plus = rt_uint32 + 1\r\n np_plus = np_uint32 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_uint32 - 1\r\n np_minus = np_uint32 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(examples=generate_sample_test_integers(num_bits=64, signed=False))\r\n def test_uint64(self, examples):\r\n for i in examples:\r\n rt_uint64 = rt.uint64(i)\r\n np_uint64 = np.uint64(i)\r\n assert_equal_(rt_uint64, np_uint64)\r\n assert isinstance(rt_uint64, type(np_uint64))\r\n\r\n rt_plus = rt_uint64 + 1\r\n np_plus = np_uint64 + 1\r\n assert_equal_(rt_plus, np_plus)\r\n assert isinstance(rt_plus, type(np_plus))\r\n\r\n rt_minus = rt_uint64 - 1\r\n np_minus = np_uint64 - 1\r\n assert_equal_(rt_minus, np_minus)\r\n assert isinstance(rt_minus, type(np_minus))\r\n\r\n @given(\r\n arr=arrays(\r\n shape=one_darray_shape_strategy(),\r\n elements=integers(-_MAX_INT, _MAX_INT),\r\n dtype=integer_dtypes(endianness=\"=\", sizes=(64,)),\r\n )\r\n )\r\n def test_unique(self, arr):\r\n rt_result = rt.unique(arr)\r\n np_result = np.unique(arr)\r\n assert_array_equal_(\r\n rt_result,\r\n np_result,\r\n err_msg=f\"arr dtype {arr.dtype} {arr}\\nrt {rt_result}\\nnp {np_result}\",\r\n )\r\n\r\n @hypothesis.settings(suppress_health_check=[HealthCheck.too_slow])\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6548 Riptable.vstack transposes arrays with shape (x,) and multiple (1,1)s. vstack also does not convert non-numbers to a FastArray\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(tuple_of_arrays=generate_tuples_of_arrays(all_same_width=True))\r\n def test_vstack(self, tuple_of_arrays):\r\n rt_err_type = None\r\n np_err_type = None\r\n rt_vstack = None\r\n np_vstack = None\r\n try:\r\n rt_vstack = rt.vstack(tuple_of_arrays)\r\n except ValueError:\r\n rt_err_type = ValueError\r\n try:\r\n np_vstack = np.vstack(tuple_of_arrays)\r\n except ValueError:\r\n np_err_type = ValueError\r\n\r\n if rt_err_type and np_err_type:\r\n assert rt_err_type == np_err_type\r\n else:\r\n assert isinstance(rt_vstack, FastArray)\r\n assert_array_equal_(np.array(rt_vstack), np_vstack)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"See TestWhere.test_where for a materialized counterexample\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(),\r\n dtype=integer_dtypes(endianness=\"=\", sizes=(32, 64)),\r\n )\r\n )\r\n def test_where(self, arr):\r\n min, mean, max = arr.min(), arr.mean(), arr.max()\r\n # Break this out into pytest cases; RiptableNumpyEquivalencyTests inherit from unittest\r\n # which does not allow for pytest.mark.parametrize.\r\n np_gt_min, rt_gt_min = np.where(arr > min), rt.where(arr > min)\r\n assert_array_equal_(\r\n np_gt_min,\r\n rt_gt_min,\r\n err_msg=f\"array elements greater than the minimum {min}\",\r\n )\r\n\r\n np_lt_mean, np_lt_mean = np.where(arr < mean), rt.where(arr < mean)\r\n assert_array_equal_(\r\n np_lt_mean, np_lt_mean, err_msg=f\"array elements less than the mean {mean}\"\r\n )\r\n\r\n np_gt_mean, np_gt_mean = np.where(arr > mean), rt.where(arr > mean)\r\n assert_array_equal_(\r\n np_gt_mean,\r\n np_gt_mean,\r\n err_msg=f\"array elements greater than the mean {mean}\",\r\n )\r\n\r\n np_lt_max, np_lt_max = np.where(arr < max), rt.where(arr < max)\r\n assert_array_equal_(\r\n np_lt_max, np_lt_max, err_msg=f\"array elements less than the max {max}\"\r\n )\r\n\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n dtype=ints_or_floats_dtypes(),\r\n order=sampled_from((\"F\", \"C\")),\r\n )\r\n def test_zeros(self, shape, dtype, order):\r\n rt_zeros = rt.zeros(shape, dtype, order)\r\n np_zeros = np.zeros(shape=shape, dtype=dtype, order=order)\r\n assert isinstance(rt_zeros, FastArray)\r\n\r\n assert_equal_(shape, rt_zeros.shape)\r\n assert_equal_(dtype.type, rt_zeros.dtype.type)\r\n assert_array_equal_(rt_zeros, np_zeros)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if len(rt_zeros.shape) > 1 and min(rt_zeros.shape) > 1:\r\n assert np.isfortran(rt_zeros) == (order == \"F\")\r\n else:\r\n assert not np.isfortran(rt_zeros)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6495 kwargs not implemented in riptable.zeros\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n shape=ndarray_shape_strategy(),\r\n dtype=ints_or_floats_dtypes(),\r\n order=sampled_from((\"F\", \"C\")),\r\n )\r\n def test_zeros_kwargs(self, shape, dtype, order):\r\n rt_zeros = rt.zeros(shape=shape, dtype=dtype, order=order)\r\n np_zeros = np.zeros(shape=shape, dtype=dtype, order=order)\r\n assert isinstance(rt_zeros, FastArray)\r\n\r\n assert_equal_(shape, rt_zeros.shape)\r\n assert_equal_(dtype.type, rt_zeros.dtype.type)\r\n assert_array_equal_(rt_zeros, np_zeros)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if len(rt_zeros.shape) > 1 and min(rt_zeros.shape) > 1:\r\n assert np.isfortran(rt_zeros) == (order == \"F\")\r\n else:\r\n assert not np.isfortran(rt_zeros)\r\n\r\n @pytest.mark.xfail(\r\n reason=\"https://jira/browse/SOQTEST-6563 riptable does not implement subok\"\r\n )\r\n @pytest.mark.skipif(\r\n is_running_in_teamcity(), reason=\"Please remove alongside xfail removal.\"\r\n )\r\n @given(\r\n arr=arrays(\r\n shape=ndarray_shape_strategy(), dtype=ints_floats_datetimes_and_timedeltas()\r\n ),\r\n dtype=ints_floats_or_complex_dtypes(),\r\n order=sampled_from((\"C\", \"F\", \"K\", \"A\")),\r\n subok=booleans(),\r\n )\r\n def test_zeros_like(self, arr, dtype, order, subok):\r\n rt_zeros_like = rt.zeros_like(arr, dtype=dtype, order=order, subok=subok)\r\n np_zeros_like = np.zeros_like(arr, dtype=dtype, order=order, subok=subok)\r\n\r\n assert_equal_(dtype, rt_zeros_like.dtype)\r\n assert_equal_(rt_zeros_like.shape, arr.shape)\r\n assert_array_equal_(rt_zeros_like, np_zeros_like)\r\n\r\n # 1-D arrays always use Column-order. Otherwise, use the order specified\r\n if (\r\n len(rt_zeros_like.shape) > 1\r\n and min(rt_zeros_like.shape) > 1\r\n and (order == \"F\" or ((order == \"A\" or order == \"K\") and np.isfortran(arr)))\r\n ):\r\n assert np.isfortran(rt_zeros_like)\r\n else:\r\n assert not np.isfortran(rt_zeros_like)\r\n\r\n if subok:\r\n assert isinstance(rt_zeros_like, FastArray)\r\n else:\r\n assert isinstance(rt_zeros_like, np.ndarray)\r\n # FastArray is a subclass of np.ndarray, so also ensure it is not a FastArray\r\n assert not isinstance(rt_zeros_like, FastArray)\r\n", "\"\"\"\r\nBenchmarks for 'merge' functions.\r\n\"\"\"\r\n__all__ = [\r\n \"bench_merge\",\r\n \"bench_merge2\",\r\n \"bench_merge2_with_settings\",\r\n \"bench_merge_pandas\",\r\n \"compare_merge\",\r\n]\r\n\r\nimport itertools\r\nimport logging\r\nimport numpy as np\r\n\r\nfrom numpy.random import default_rng\r\nfrom itertools import product\r\nfrom typing import List, Tuple\r\n\r\nfrom .benchmark import timestamper\r\nfrom .rand_data import rand_dataset\r\nfrom .runner import create_comparison_dataset, create_trial_dataset, benchmark\r\nfrom ..rt_categorical import Categorical\r\nfrom ..rt_dataset import Dataset\r\nfrom ..rt_merge import merge, merge2\r\nfrom ..rt_numpy import empty\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\"\"\"The logger for this module.\"\"\"\r\n\r\n\r\ndef _range_slice(s: slice, endpoint: bool = True) -> List[int]:\r\n \"\"\"\r\n Create a list of integers as specified by the slice.\r\n\r\n Parameters\r\n ----------\r\n s : slice\r\n endpoint : bool\r\n\r\n Returns\r\n -------\r\n slice_indices : list of int\r\n\r\n Examples\r\n --------\r\n >>> _range_slice(slice(200, 500, 50))\r\n [200,\r\n 250,\r\n 300,\r\n 350,\r\n 400,\r\n 450,\r\n 500]\r\n \"\"\"\r\n # If the caller wants the right endpoint to be included, adjust\r\n # the 'stop' value by 1 (or -1) so the .indices() method includes it.\r\n if endpoint:\r\n adjust = 1 if s.step >= 0 else -1\r\n s = slice(s.start, s.stop + adjust, s.step)\r\n return list(range(*(s.indices(s.stop))))\r\n\r\n\r\ndef generate_merge_datasets(\r\n rng_seed=12345,\r\n left_key_unique_count=25,\r\n right_key_unique_count=2500,\r\n left_dataset_max_rowcount=250_000,\r\n right_dataset_max_rowcount=62_500,\r\n) -> Tuple[Dataset, Dataset]:\r\n \"\"\"Generates the left and right Datasets for merge benchmarking.\"\"\"\r\n left_step = int(left_dataset_max_rowcount / 4)\r\n left_rowcounts = list(range(left_step, left_dataset_max_rowcount + 1, left_step))\r\n right_step = int(right_dataset_max_rowcount / 4)\r\n right_rowcounts = list(\r\n range(right_step, right_dataset_max_rowcount + 1, right_step)\r\n )\r\n\r\n left_datasets, right_datasets = list(), list()\r\n for left_rowcount in left_rowcounts:\r\n for right_rowcount in right_rowcounts:\r\n rng = default_rng(rng_seed)\r\n left_datasets.append(\r\n rand_dataset(left_rowcount, rng, left_key_unique_count)\r\n )\r\n right_datasets.append(\r\n rand_dataset(right_rowcount, rng, right_key_unique_count)\r\n )\r\n return left_datasets, right_datasets\r\n\r\n\r\ndef bench_merge(**kwargs) -> Dataset:\r\n # TODO: Add additional dimensions:\r\n # * key is Cat [True, False]\r\n # * key dtype(s) -- use this to also bench with multiple keys\r\n # * number of threads\r\n # * recycler on/off\r\n # * number of additional (non-key) columns in the left and/or right (just make them all the same dtype, it doesn't matter much for this benchmark)\r\n # * (advanced) different key distributions\r\n # * (advanced) key clustering (i.e. are keys already more or less occurring near each other, or are they all spread out?)\r\n # * (advanced) key dispersion -- if the unique keys are created like arange(1, 100), does grouping/merge go any\r\n # faster than if the keys are created like arange(1, 1000, 10) or arange(1, 1_000_000_000, 10_000_000_000)?\r\n # Make sure to control for dtype to ensure that's the same for all cases tested here.\r\n # This could be used to diagnose issues with hashing/grouping implementations.\r\n\r\n # Fixed parameters which apply to all of the trials in this benchmark.\r\n warmup_iters = 1\r\n iters = 5\r\n\r\n # Setup parameters.\r\n rng_seeds = [12345]\r\n left_key_unique_counts = [100]\r\n right_key_unique_counts = [10000]\r\n left_rowcounts = _range_slice(slice(500_000, 2_000_000, 500_000))\r\n right_rowcounts = _range_slice(slice(250_000, 500_000, 250_000))\r\n\r\n setup_params = itertools.product(\r\n rng_seeds,\r\n left_key_unique_counts,\r\n right_key_unique_counts,\r\n left_rowcounts,\r\n right_rowcounts,\r\n )\r\n\r\n # Trial parameters.\r\n hows = [\"left\", \"right\", \"inner\"] # TODO: Add 'outer'; seems to be broken though?\r\n trial_params = hows\r\n\r\n # Datasets containing timing data and parameters from the trials in this benchmark.\r\n benchmark_data: List[Dataset] = []\r\n\r\n for (\r\n rng_seed,\r\n left_key_unique_count,\r\n right_key_unique_count,\r\n left_rowcount,\r\n right_rowcount,\r\n ) in setup_params:\r\n #\r\n # Setup phase. The data here is used for both the warmup and the real, timed function invocations.\r\n #\r\n # Make sure to re-initialize the RNG each time so we get a repeatable result.\r\n rng = default_rng(rng_seed)\r\n\r\n left_ds = rand_dataset(left_rowcount, rng, left_key_unique_count)\r\n right_ds = rand_dataset(right_rowcount, rng, right_key_unique_count)\r\n\r\n # Sweep over trial parameters; all trials sharing the same setup parameters\r\n # share the same data created from those setup parameters.\r\n for how in trial_params:\r\n # Allocate an array to hold the raw timing data.\r\n # TODO: Change to use TimeSpan?\r\n timing_data = empty(iters, dtype=np.int64)\r\n\r\n for is_warmup in (True, False):\r\n loop_count = warmup_iters if is_warmup else iters\r\n logger.info(\r\n f\"bench_merge:\\tmode={'warmup' if is_warmup else 'bench'}\\tloops={loop_count}\\tleft_rowcount={left_rowcount}\\tright_rowcount={right_rowcount}\\thow={how}\"\r\n )\r\n\r\n for i in range(loop_count):\r\n start_time_ns = timestamper()\r\n\r\n ### The actual function invocation ###\r\n # TODO: This could be passed in as a lambda, and we call it with the data constructed\r\n # in the setup phase + any \"parameters\" that weren't used in the setup phase; or for\r\n # simplicity just pass all the parameters + the data constructed in the setup phase,\r\n # the lambda doesn't need to use all of it.\r\n\r\n merge(left_ds, right_ds, on=\"key\", how=how)\r\n\r\n ### Store the timing results (if this was a real invocation).\r\n call_nanos = timestamper() - start_time_ns\r\n if not is_warmup:\r\n timing_data[i] = call_nanos\r\n\r\n # Create a mini Dataset with the timing results for this run.\r\n # Capture the timing results along with the other options used for the function invocations.\r\n trial_data = create_trial_dataset(\r\n timing_data,\r\n {\r\n # Setup parameters\r\n \"rng_seed\": rng_seed,\r\n \"left_key_unique_count\": left_key_unique_count,\r\n \"right_key_unique_count\": right_key_unique_count,\r\n \"left_rowcount\": left_rowcount,\r\n \"right_rowcount\": right_rowcount,\r\n # Trial parameters\r\n \"how\": how,\r\n },\r\n )\r\n benchmark_data.append(trial_data)\r\n\r\n # hstack all of the individual Datasets together into one large Dataset and return it.\r\n return Dataset.hstack(benchmark_data, destroy=True)\r\n\r\n\r\ndef bench_merge2(**kwargs) -> Dataset:\r\n # TODO: Add additional dimensions:\r\n # * key is Cat [True, False]\r\n # * key dtype(s) -- use this to also bench with multiple keys\r\n # * number of threads\r\n # * recycler on/off\r\n # * number of additional (non-key) columns in the left and/or right (just make them all the same dtype, it doesn't matter much for this benchmark)\r\n # * (advanced) different key distributions\r\n # * (advanced) key clustering (i.e. are keys already more or less occurring near each other, or are they all spread out?)\r\n # * (advanced) key dispersion -- if the unique keys are created like arange(1, 100), does grouping/merge go any\r\n # faster than if the keys are created like arange(1, 1000, 10) or arange(1, 1_000_000_000, 10_000_000_000)?\r\n # Make sure to control for dtype to ensure that's the same for all cases tested here.\r\n # This could be used to diagnose issues with hashing/grouping implementations.\r\n\r\n # Fixed parameters which apply to all of the trials in this benchmark.\r\n warmup_iters = 1\r\n iters = 5\r\n\r\n # Setup parameters.\r\n rng_seeds = [12345]\r\n left_key_unique_counts = [100]\r\n right_key_unique_counts = [10000]\r\n left_rowcounts = _range_slice(\r\n slice(500_000, 2_000_000, 500_000)\r\n ) # TODO: For larger-memory machines, we could use a larger max here, e.g. 7M\r\n right_rowcounts = _range_slice(\r\n slice(250_000, 500_000, 250_000)\r\n ) # TODO: For larger-memory machines, we could use a larger max here, e.g. 5M\r\n\r\n setup_params = itertools.product(\r\n rng_seeds,\r\n left_key_unique_counts,\r\n right_key_unique_counts,\r\n left_rowcounts,\r\n right_rowcounts,\r\n )\r\n\r\n # Trial parameters.\r\n hows = [\r\n \"left\",\r\n \"right\",\r\n \"inner\",\r\n ] # TODO: Add 'outer'; skip 'right', that's the same logic as left\r\n left_keeps = [None, \"first\", \"last\"]\r\n right_keeps = [None, \"first\", \"last\"]\r\n\r\n trial_params = lambda: itertools.product(hows, left_keeps, right_keeps)\r\n\r\n # Datasets containing timing data and parameters from the trials in this benchmark.\r\n benchmark_data: List[Dataset] = []\r\n\r\n for (\r\n rng_seed,\r\n left_key_unique_count,\r\n right_key_unique_count,\r\n left_rowcount,\r\n right_rowcount,\r\n ) in setup_params:\r\n #\r\n # Setup phase. The data here is used for both the warmup and the real, timed function invocations.\r\n #\r\n # Make sure to re-initialize the RNG each time so we get a repeatable result.\r\n rng = default_rng(rng_seed)\r\n\r\n left_ds = rand_dataset(left_rowcount, rng, left_key_unique_count)\r\n right_ds = rand_dataset(right_rowcount, rng, right_key_unique_count)\r\n\r\n # Sweep over trial parameters; all trials sharing the same setup parameters\r\n # share the same data created from those setup parameters.\r\n for how, keep_left, keep_right in trial_params():\r\n # Allocate an array to hold the raw timing data.\r\n # TODO: Change to use TimeSpan?\r\n timing_data = empty(iters, dtype=np.int64)\r\n\r\n for is_warmup in (True, False):\r\n loop_count = warmup_iters if is_warmup else iters\r\n logger.info(\r\n f\"bench_merge2:\\tmode={'warmup' if is_warmup else 'bench'}\\tloops={loop_count}\\tleft_rowcount={left_rowcount}\\tright_rowcount={right_rowcount}\\thow={how}\\tkeep_left={keep_left}\\tkeep_right={keep_right}\"\r\n )\r\n\r\n for i in range(loop_count):\r\n start_time_ns = timestamper()\r\n\r\n ### The actual function invocation ###\r\n # TODO: This could be passed in as a lambda, and we call it with the data constructed\r\n # in the setup phase + any \"parameters\" that weren't used in the setup phase; or for\r\n # simplicity just pass all the parameters + the data constructed in the setup phase,\r\n # the lambda doesn't need to use all of it.\r\n keep = keep_left, keep_right\r\n merge2(\r\n left_ds,\r\n right_ds,\r\n on=\"key\",\r\n how=how,\r\n keep=keep,\r\n suffixes=(\"_x\", \"_y\"),\r\n )\r\n\r\n ### Store the timing results (if this was a real invocation).\r\n call_nanos = timestamper() - start_time_ns\r\n if not is_warmup:\r\n timing_data[i] = call_nanos\r\n\r\n # Create a mini Dataset with the timing results for this run.\r\n # Capture the timing results along with the other options used for the function invocations.\r\n trial_data = create_trial_dataset(\r\n timing_data,\r\n {\r\n # Setup parameters\r\n \"rng_seed\": rng_seed,\r\n \"left_key_unique_count\": left_key_unique_count,\r\n \"right_key_unique_count\": right_key_unique_count,\r\n \"left_rowcount\": left_rowcount,\r\n \"right_rowcount\": right_rowcount,\r\n # Trial parameters\r\n \"how\": how,\r\n \"keep_left\": \"\" if keep_left is None else keep_left,\r\n \"keep_right\": \"\" if keep_right is None else keep_right,\r\n },\r\n )\r\n benchmark_data.append(trial_data)\r\n\r\n # hstack all of the individual Datasets together into one large Dataset and return it.\r\n return Dataset.hstack(benchmark_data, destroy=True)\r\n\r\n\r\ndef bench_merge2_with_settings():\r\n # Define the dimensions (and their values) we want to sweep over for the benchmarking\r\n how_options = [\r\n \"left\",\r\n \"right\",\r\n \"inner\",\r\n ] # TODO: Add 'outer'; skip 'right', that's the same logic as left\r\n keeps = [None, \"first\", \"last\"]\r\n keep_options = list(product(keeps, keeps))\r\n left_datasets, right_datasets = generate_merge_datasets()\r\n warmup_iters, benchmark_iters = 1, 5\r\n\r\n @benchmark(\r\n benchmark_params={\r\n # _merge2 parameters\r\n \"left_ds\": left_datasets,\r\n \"right_ds\": right_datasets,\r\n \"on\": [\"key\"],\r\n \"how\": how_options,\r\n \"keeps\": keep_options,\r\n # riptable settings\r\n \"thread_count\": [1, 2, 4, 8],\r\n \"recycler\": [True, False],\r\n },\r\n # benchmark options\r\n warmup_iterations=warmup_iters,\r\n benchmark_iterations=benchmark_iters,\r\n enable_bench_estimators=True, # TODO\r\n )\r\n def bench_merge2(left_ds, right_ds, on, how, keeps):\r\n merge2(left_ds, right_ds, on=on, how=how, keep=keeps, suffixes=(\"_x\", \"_y\"))\r\n\r\n return bench_merge2()\r\n\r\n\r\ndef bench_merge_pandas(**kwargs) -> Dataset:\r\n \"\"\"Merge benchmark for pandas.\"\"\"\r\n import pandas as pd\r\n\r\n # Fixed parameters which apply to all of the trials in this benchmark.\r\n warmup_iters = 1\r\n iters = 5\r\n\r\n # Setup parameters.\r\n rng_seeds = [12345]\r\n left_key_unique_counts = [100]\r\n right_key_unique_counts = [10000]\r\n left_rowcounts = _range_slice(\r\n slice(500_000, 2_000_000, 500_000)\r\n ) # TODO: For larger-memory machines, we could use a larger max here, e.g. 7M\r\n right_rowcounts = _range_slice(\r\n slice(250_000, 500_000, 250_000)\r\n ) # TODO: For larger-memory machines, we could use a larger max here, e.g. 5M\r\n\r\n setup_params = itertools.product(\r\n rng_seeds,\r\n left_key_unique_counts,\r\n right_key_unique_counts,\r\n left_rowcounts,\r\n right_rowcounts,\r\n )\r\n\r\n # Trial parameters.\r\n hows = [\r\n \"left\",\r\n \"right\",\r\n \"inner\",\r\n ] # TODO: Add 'outer' once we add it for merge and merge2.\r\n left_keeps = [None, \"first\", \"last\"]\r\n right_keeps = [None, \"first\", \"last\"]\r\n\r\n trial_params = lambda: itertools.product(hows, left_keeps, right_keeps)\r\n\r\n # Datasets containing timing data and parameters from the trials in this benchmark.\r\n benchmark_data: List[Dataset] = []\r\n\r\n for (\r\n rng_seed,\r\n left_key_unique_count,\r\n right_key_unique_count,\r\n left_rowcount,\r\n right_rowcount,\r\n ) in setup_params:\r\n #\r\n # Setup phase. The data here is used for both the warmup and the real, timed function invocations.\r\n #\r\n # Make sure to re-initialize the RNG each time so we get a repeatable result.\r\n rng = default_rng(rng_seed)\r\n\r\n left_df = rand_dataset(left_rowcount, rng, left_key_unique_count).to_pandas(\r\n use_nullable=True\r\n )\r\n right_df = rand_dataset(right_rowcount, rng, right_key_unique_count).to_pandas(\r\n use_nullable=True\r\n )\r\n\r\n # Sweep over trial parameters; all trials sharing the same setup parameters\r\n # share the same data created from those setup parameters.\r\n for how, keep_left, keep_right in trial_params():\r\n # Allocate an array to hold the raw timing data.\r\n # TODO: Change to use TimeSpan?\r\n timing_data = empty(iters, dtype=np.int64)\r\n\r\n for is_warmup in (True, False):\r\n loop_count = warmup_iters if is_warmup else iters\r\n\r\n for i in range(loop_count):\r\n start_time_ns = timestamper()\r\n\r\n ### The actual function invocation ###\r\n # Pandas merge doesn't support 'keep' (yet: see https://github.com/pandas-dev/pandas/issues/31332 ),\r\n # so we need to do it manually with drop_duplicates first.\r\n if keep_left is not None:\r\n left_df = left_df.drop_duplicates(subset=\"key\", keep=keep_left)\r\n if keep_right is not None:\r\n right_df = right_df.drop_duplicates(\r\n subset=\"key\", keep=keep_right\r\n )\r\n\r\n left_df.merge(right_df, on=\"key\", how=how)\r\n ### Actual function invocation ends here ###\r\n\r\n ### Store the timing results (if this was a real invocation).\r\n call_nanos = timestamper() - start_time_ns\r\n if not is_warmup:\r\n timing_data[i] = call_nanos\r\n\r\n # Create a mini Dataset with the timing results for this run.\r\n # Capture the timing results along with the other options used for the function invocations.\r\n trial_data = create_trial_dataset(\r\n timing_data,\r\n {\r\n # Setup parameters\r\n \"rng_seed\": rng_seed,\r\n \"left_key_unique_count\": left_key_unique_count,\r\n \"right_key_unique_count\": right_key_unique_count,\r\n \"left_rowcount\": left_rowcount,\r\n \"right_rowcount\": right_rowcount,\r\n # Trial parameters\r\n \"how\": how,\r\n \"keep_left\": \"\" if keep_left is None else keep_left,\r\n \"keep_right\": \"\" if keep_right is None else keep_right,\r\n },\r\n )\r\n benchmark_data.append(trial_data)\r\n\r\n # hstack all of the individual Datasets together into one large Dataset and return it.\r\n return Dataset.hstack(benchmark_data, destroy=True)\r\n\r\n\r\ndef compare_merge(**kwargs) -> Dataset:\r\n \"\"\"Run all 'merge' benchmarks and return the combined results.\"\"\"\r\n\r\n # Run the benchmark for rt.merge.\r\n rtmerge_bench_data = bench_merge(**kwargs)\r\n\r\n # Using the 'how' column and our knowledge of how rt.merge operates,\r\n # synthesize 'keep_left' and 'keep_right' Categoricals for the rt.merge\r\n # results so they can be better compared to the other implementations.\r\n # TODO: This could be removed in the future once we support jagged/non-rectangular\r\n # benchmark parameters, since we can pass these in to the benchmark\r\n # and have them recorded in the usual way.\r\n rtmerge_bench_data[\"keep_left\"] = Categorical(\r\n rtmerge_bench_data[\"how\"].map(\r\n {\"right\": \"last\", \"inner\": \"last\", \"outer\": \"last\"}, invalid=\"\"\r\n )\r\n )\r\n rtmerge_bench_data[\"keep_right\"] = Categorical(\r\n rtmerge_bench_data[\"how\"].map(\r\n {\"left\": \"last\", \"inner\": \"last\", \"outer\": \"last\"}, invalid=\"\"\r\n )\r\n )\r\n\r\n # Run the benchmark for rt.merge2.\r\n rtmerge2_bench_data = bench_merge2(**kwargs)\r\n\r\n # Run the benchmark for pandas.\r\n pdmerge_bench_data = bench_merge_pandas(**kwargs)\r\n\r\n # Combine the results for the different implementations into\r\n # a single Dataset and return it.\r\n return create_comparison_dataset(\r\n {\r\n \"rt_merge\": rtmerge_bench_data,\r\n \"rt_merge2\": rtmerge2_bench_data,\r\n \"pandas\": pdmerge_bench_data,\r\n },\r\n destroy=True,\r\n )\r\n" ]
[ [ "numpy.testing.assert_almost_equal" ], [ "pandas.util.testing.makeTimeDataFrame", "numpy.testing.assert_almost_equal", "pandas.DataFrame" ], [ "numpy.minimum", "numpy.sqrt", "numpy.cumsum", "numpy.nan_to_num", "numpy.dtype", "numpy.all", "numpy.concatenate", "numpy.round", "numpy.zeros_like", "numpy.any", "numpy.searchsorted", "numpy.nanstd", "numpy.where", "numpy.double", "numpy.hstack", "numpy.trunc", "numpy.ones_like", "numpy.uint32", "numpy.unique", "numpy.reshape", "numpy.arange", "numpy.uint8", "numpy.nanvar", "numpy.int8", "numpy.lexsort", "numpy.full", "numpy.ceil", "numpy.std", "numpy.nansum", "numpy.diff", "numpy.interp", "numpy.float32", "numpy.uint16", "numpy.repeat", "numpy.zeros", "numpy.log", "numpy.putmask", "numpy.min", "numpy.isnan", "numpy.quantile", "numpy.int64", "numpy.log10", "numpy.floor", "numpy.testing.assert_allclose", "numpy.argsort", "numpy.array", "numpy.sum", "numpy.nanpercentile", "numpy.absolute", "numpy.maximum", "numpy.abs", "numpy.isfinite", "numpy.isfortran", "numpy.int32", "numpy.tile", "numpy.percentile", "numpy.ones", "numpy.int16", "numpy.uint64", "numpy.bincount", "numpy.float64", "numpy.isinf", "numpy.vstack" ], [ "numpy.random.default_rng" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vik748/OpenSfM
[ "bd949246e3e0d6d3a707a08224038034d27e3ee8", "569144c26df860cfa45d183f7701d0414e35d086" ]
[ "scripts/track_length_analysis_test.py", "opensfm/test/test_triangulation.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 19 08:11:51 2021\n\n@author: vik748\n\"\"\"\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys,os\nimport pandas as pd\n\ndef tracks_histogram(recon_file, tracks_file, ax, model_num=0, bins=np.linspace(2,15,14)):\n '''\n How the tracks.csv file is written\n template <class S>\n void WriteToStreamCurrentVersion(S& ostream, const TracksManager& manager) {\n ostream << manager.TRACKS_HEADER << \"_v\" << manager.TRACKS_VERSION\n << std::endl;\n const auto shotsIDs = manager.GetShotIds();\n for (const auto& shotID : shotsIDs) {\n const auto observations = manager.GetShotObservations(shotID);\n for (const auto& observation : observations) {\n ostream << shotID << \"\\t\" << observation.first << \"\\t\"\n << observation.second.id << \"\\t\" << observation.second.point(0)\n << \"\\t\" << observation.second.point(1) << \"\\t\"\n << observation.second.scale << \"\\t\" << observation.second.color(0)\n << \"\\t\" << observation.second.color(1) << \"\\t\"\n << observation.second.color(2) << std::endl;\n }\n }\n }\n\n '''\n with open(recon_file) as f:\n data = json.load(f)\n\n if model_num == -1:\n points_dict = {}\n for d in data:\n points_dict.update(d['points'])\n\n else:\n points_dict = data[model_num]['points']\n\n model_0_point_ids_int = [int(k) for k in points_dict.keys()]\n\n tracks_df = pd.read_csv(tracks_file, sep='\\t', skiprows=1,\n names=['image', 'track_id', 'feature_id', 'x', 'y',\n 'scale', 'r', 'g', 'b'])\n track_id_counts = tracks_df.track_id.value_counts()\n\n\n model_0_track_id_counts = track_id_counts[model_0_point_ids_int]\n\n ax.hist(model_0_track_id_counts, bins=bins)\n\n return model_0_track_id_counts\n\n\n########################################\n# Skerki_mud SIFT - RAW vs CLAHE - Model 0\n########################################\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_SIFT_tracks.csv'\n\nfig1, ax = plt.subplots(nrows=2, sharex=True, sharey=True)\nfig1.suptitle('Skerki Mud SIFT')\n\ntracks_histogram(recon_file, tracks_file, ax[0], bins=np.linspace(2,15,14))\n\nax[0].set_xlim([2, None])\nax[0].set_yscale('log')\nax[0].set_ylim([None, 10000])\nax[0].set_title('RAW')\nax[0].set_xlabel('Feature Track Length')\nax[0].set_ylabel('Fequency')\nax[0].xaxis.set_major_locator(plt.MultipleLocator(1))\n\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_CLAHE_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_CLAHE_SIFT_tracks.csv'\n\n\ntracks_histogram(recon_file, tracks_file, ax[1], bins=np.linspace(2,15,14))\nax[1].set_title('CLAHE')\nax[1].set_xlabel('Feature Track Length')\nax[1].set_ylabel('Fequency')\n\n\n########################################\n# Skerki_mud RAW - SIFT vs Zernike\n########################################\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_SIFT_tracks.csv'\n\nfig2, ax = plt.subplots(nrows=2, sharex=True, sharey=True)\nfig2.suptitle('Skerki Mud RAW')\n\ntracks_histogram(recon_file, tracks_file, ax[0], bins=np.linspace(2,15,14))\n\nax[0].set_xlim([2, None])\nax[0].set_yscale('log')\nax[0].set_ylim([None, 10000])\nax[0].set_title('SIFT')\nax[0].set_xlabel('Feature Track Length')\nax[0].set_ylabel('Fequency')\nax[0].xaxis.set_major_locator(plt.MultipleLocator(1))\n\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_ZERNIKE_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_ZERNIKE_tracks.csv'\n\n\ntracks_histogram(recon_file, tracks_file, ax[1], model_num=1, bins=np.linspace(2,15,14))\nax[1].set_title('ZERNIKE')\nax[1].set_xlabel('Feature Track Length')\nax[1].set_ylabel('Fequency')\n\n########################################\n# Skerki_mud Zernike - RAW vs CLAHE\n########################################\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_ZERNIKE_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_ZERNIKE_tracks.csv'\n\nfig3, ax = plt.subplots(nrows=2, sharex=True, sharey=True)\nfig3.suptitle('Skerki Mud ZERNIKE')\n\ntracks_histogram(recon_file, tracks_file, ax[0], model_num=1, bins=np.linspace(2,15,14))\n\nax[0].set_xlim([2, None])\nax[0].set_yscale('log')\nax[0].set_ylim([None, 10000])\nax[0].set_title('RAW')\nax[0].set_xlabel('Feature Track Length')\nax[0].set_ylabel('Fequency')\nax[0].xaxis.set_major_locator(plt.MultipleLocator(1))\n\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_CLAHE_ZERNIKE_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_CLAHE_ZERNIKE_tracks.csv'\n\n\ntracks_histogram(recon_file, tracks_file, ax[1], bins=np.linspace(2,15,14))\nax[1].set_title('CLAHE')\nax[1].set_xlabel('Feature Track Length')\nax[1].set_ylabel('Fequency')\n\n\n########################################\n# Stingray - SIFT vs Zernike\n########################################\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_SIFT_tracks.csv'\n\nfig4, ax = plt.subplots(nrows=2, sharex=True, sharey=True)\nfig4.suptitle('Stingray RAW')\n\ntracks_histogram(recon_file, tracks_file, ax[0], bins=np.linspace(2,15,14))\n\nax[0].set_xlim([2, None])\nax[0].set_yscale('log')\nax[0].set_ylim([None, 10000])\nax[0].set_title('SIFT')\nax[0].set_xlabel('Feature Track Length')\nax[0].set_ylabel('Fequency')\nax[0].xaxis.set_major_locator(plt.MultipleLocator(1))\n\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_ZERNIKE_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_ZERNIKE_tracks.csv'\n\n\ntracks_histogram(recon_file, tracks_file, ax[1], bins=np.linspace(2,15,14))\nax[1].set_title('ZERNIKE')\nax[1].set_xlabel('Feature Track Length')\nax[1].set_ylabel('Fequency')\n\n########################################\n# Skerki_mud SIFT - RAW vs CLAHE - Combined\n########################################\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_RAW_SIFT_tracks.csv'\n\nfig5, ax = plt.subplots(nrows=2, sharex=True, sharey=True)\nfig5.suptitle('Skerki Mud SIFT - Combined')\n\ntracks_histogram(recon_file, tracks_file, ax[0], model_num=-1, bins=np.linspace(2,15,14))\n\nax[0].set_xlim([2, None])\nax[0].set_yscale('log')\nax[0].set_ylim([None, 10000])\nax[0].set_title('RAW')\nax[0].set_xlabel('Feature Track Length')\nax[0].set_ylabel('Fequency')\nax[0].xaxis.set_major_locator(plt.MultipleLocator(1))\n\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_CLAHE_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Skerki_mud/Skerki_mud_CLAHE_SIFT_tracks.csv'\n\n\ntracks_histogram(recon_file, tracks_file, ax[1], bins=np.linspace(2,15,14))\nax[1].set_title('CLAHE')\nax[1].set_xlabel('Feature Track Length')\nax[1].set_ylabel('Fequency')\n\n########################################\n# Stingray SIFT - RAW vs CLAHE\n########################################\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_SIFT_tracks.csv'\n\nfig6, ax = plt.subplots(nrows=2, sharex=True, sharey=True)\nfig6.suptitle('Stingray SIFT')\n\ntracks_histogram(recon_file, tracks_file, ax[0], bins=np.linspace(2,15,14))\n\nax[0].set_xlim([2, None])\nax[0].set_yscale('log')\nax[0].set_ylim([None, 10000])\nax[0].set_title('RAW')\nax[0].set_xlabel('Feature Track Length')\nax[0].set_ylabel('Fequency')\nax[0].xaxis.set_major_locator(plt.MultipleLocator(1))\n\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_CLAHE_SIFT_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_CLAHE_SIFT_tracks.csv'\n\ntracks_histogram(recon_file, tracks_file, ax[1], bins=np.linspace(2,15,14))\nax[1].set_title('CLAHE')\nax[1].set_xlabel('Feature Track Length')\nax[1].set_ylabel('Fequency')\n\n########################################\n# Stingray Zernike - RAW vs CLAHE\n########################################\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_ZERNIKE_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_ZERNIKE_tracks.csv'\n\nfig7, ax = plt.subplots(nrows=2, sharex=True, sharey=True)\nfig7.suptitle('Stingray ZERNIKE')\n\ncounts0 = tracks_histogram(recon_file, tracks_file, ax[0], bins=np.linspace(2,15,14))\n\nax[0].set_xlim([2, None])\nax[0].set_yscale('log')\nax[0].set_ylim([None, 10000])\nax[0].set_title('RAW')\nax[0].set_xlabel('Feature Track Length')\nax[0].set_ylabel('Fequency')\nax[0].xaxis.set_major_locator(plt.MultipleLocator(1))\n\nrecon_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_CLAHE_ZERNIKE_reconstruction.json'\ntracks_file = '/home/vik748/data/OpenSfM_data/track_length_test_data/Stingray/Stingray_CLAHE_ZERNIKE_tracks.csv'\n\ncounts1 = tracks_histogram(recon_file, tracks_file, ax[1], bins=np.linspace(2,15,14))\nax[1].set_title('CLAHE')\nax[1].set_xlabel('Feature Track Length')\nax[1].set_ylabel('Fequency')\n\n\n\nplt.hist([counts1, counts2], np.linspace(2,15,14), label=['RAW', 'CLAHE'])\nplt.legend(loc='upper right')\nplt.show()\n", "import numpy as np\nimport networkx as nx\n\nfrom opensfm import io\nfrom opensfm import pygeometry\nfrom opensfm import reconstruction\nfrom opensfm import pysfm\n\n\ndef test_track_triangulator_equirectangular():\n \"\"\"Test triangulating tracks of spherical images.\"\"\"\n tracks_manager = pysfm.TracksManager()\n tracks_manager.add_observation('im1', '1', pysfm.Observation(0, 0, 1.0, 0, 0, 0, 0))\n tracks_manager.add_observation('im2', '1', pysfm.Observation(-0.1, 0, 1.0, 0, 0, 0, 1))\n\n rec = io.reconstruction_from_json({\n \"cameras\": {\n \"theta\": {\n \"projection_type\": \"equirectangular\",\n \"width\": 800,\n \"height\": 400,\n }\n },\n\n \"shots\": {\n 'im1': {\n \"camera\": \"theta\",\n \"rotation\": [0.0, 0.0, 0.0],\n \"translation\": [0.0, 0.0, 0.0],\n },\n 'im2': {\n \"camera\": \"theta\",\n \"rotation\": [0, 0, 0.0],\n \"translation\": [-1, 0, 0.0],\n },\n },\n\n \"points\": {\n },\n })\n\n triangulator = reconstruction.TrackTriangulator(tracks_manager, rec)\n triangulator.triangulate('1', 0.01, 2.0)\n assert '1' in rec.points\n p = rec.points['1'].coordinates\n assert np.allclose(p, [0, 0, 1.3763819204711])\n assert len(rec.points['1'].get_observations()) == 2\n\n\ndef unit_vector(x):\n return np.array(x) / np.linalg.norm(x)\n\n\ndef test_triangulate_bearings_dlt():\n rt1 = np.append(np.identity(3), [[0], [0], [0]], axis=1)\n rt2 = np.append(np.identity(3), [[-1], [0], [0]], axis=1)\n b1 = unit_vector([0.0, 0, 1])\n b2 = unit_vector([-1.0, 0, 1])\n max_reprojection = 0.01\n min_ray_angle = np.radians(2.0)\n res, X = pygeometry.triangulate_bearings_dlt(\n [rt1, rt2], [b1, b2], max_reprojection, min_ray_angle)\n assert np.allclose(X, [0, 0, 1.0])\n assert res is True\n\n\ndef test_triangulate_bearings_midpoint():\n o1 = np.array([0.0, 0, 0])\n b1 = unit_vector([0.0, 0, 1])\n o2 = np.array([1.0, 0, 0])\n b2 = unit_vector([-1.0, 0, 1])\n max_reprojection = 0.01\n min_ray_angle = np.radians(2.0)\n res, X = pygeometry.triangulate_bearings_midpoint(\n [o1, o2], [b1, b2], 2 * [max_reprojection], min_ray_angle)\n assert np.allclose(X, [0, 0, 1.0])\n assert res is True\n\n\ndef test_triangulate_two_bearings_midpoint():\n o1 = np.array([0.0, 0, 0])\n b1 = unit_vector([0.0, 0, 1])\n o2 = np.array([1.0, 0, 0])\n b2 = unit_vector([-1.0, 0, 1])\n max_reprojection = 0.01\n min_ray_angle = np.radians(2.0)\n X = pygeometry.triangulate_two_bearings_midpoint([o1, o2], [b1, b2])\n assert np.allclose(X, [0, 0, 1.0])\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "numpy.linspace", "matplotlib.pyplot.subplots", "matplotlib.pyplot.MultipleLocator", "matplotlib.pyplot.show" ], [ "numpy.radians", "numpy.allclose", "numpy.linalg.norm", "numpy.identity", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
prkkumar/WarpX
[ "a83c9c03ecc9850cd724efc14075eb95ff8a6138" ]
[ "Python/pywarpx/fields.py" ]
[ "# Copyright 2017-2019 David Grote\n#\n# This file is part of WarpX.\n#\n# License: BSD-3-Clause-LBNL\n\n\"\"\"Provides wrappers around field and current density on multiFABs\n\nAvailable routines:\n\nExWrapper, EyWrapper, EzWrapper\nBxWrapper, ByWrapper, BzWrapper\nJxWrapper, JyWrapper, JzWrapper\n\n\"\"\"\nimport numpy as np\ntry:\n from mpi4py import MPI as mpi\n comm_world = mpi.COMM_WORLD\n npes = comm_world.Get_size()\nexcept ImportError:\n npes = 1\n\nfrom . import _libwarpx\n\n\nclass _MultiFABWrapper(object):\n \"\"\"Wrapper around field arrays at level 0\n This provides a convenient way to query and set fields that are broken up into FABs.\n The indexing is based on global indices.\n - direction: component to access, one of the values (0, 1, 2) or None\n - get_lovects: routine that returns the list of lo vectors\n - get_fabs: routine that returns the list of FABs\n - get_nodal_flag: routine that returns the list of nodal flag\n - level: refinement level\n \"\"\"\n def __init__(self, direction, get_lovects, get_fabs, get_nodal_flag, level, include_ghosts=False):\n self.direction = direction\n self.get_lovects = get_lovects\n self.get_fabs = get_fabs\n self.get_nodal_flag = get_nodal_flag\n self.level = level\n self.include_ghosts = include_ghosts\n\n self.dim = _libwarpx.dim\n\n # overlaps is one along the axes where the grid boundaries overlap the neighboring grid,\n # which is the case with node centering.\n # This presumably will never change during a calculation.\n self.overlaps = self.get_nodal_flag()\n\n def _getlovects(self):\n if self.direction is None:\n lovects, ngrow = self.get_lovects(self.level, self.include_ghosts)\n else:\n lovects, ngrow = self.get_lovects(self.level, self.direction, self.include_ghosts)\n return lovects, ngrow\n\n def _gethivects(self):\n lovects, ngrow = self._getlovects()\n fields = self._getfields()\n\n hivects = np.zeros_like(lovects)\n for i in range(len(fields)):\n hivects[:,i] = lovects[:,i] + np.array(fields[i].shape[:self.dim]) - self.overlaps\n\n return hivects, ngrow\n\n def _getfields(self):\n if self.direction is None:\n return self.get_fabs(self.level, self.include_ghosts)\n else:\n return self.get_fabs(self.level, self.direction, self.include_ghosts)\n\n def __len__(self):\n lovects, ngrow = self._getlovects()\n return len(lovects)\n\n def mesh(self, direction):\n \"\"\"Returns the mesh along the specified direction with the appropriate centering.\n - direction: In 3d, one of 'x', 'y', or 'z'.\n In 2d, Cartesian, one of 'x', or 'z'.\n In RZ, one of 'r', or 'z'\n \"\"\"\n\n try:\n if _libwarpx.geometry_dim == '3d':\n idir = ['x', 'y', 'z'].index(direction)\n celldir = idir\n elif _libwarpx.geometry_dim == '2d':\n idir = ['x', 'z'].index(direction)\n celldir = 2*idir\n elif _libwarpx.geometry_dim == 'rz':\n idir = ['r', 'z'].index(direction)\n celldir = 2*idir\n except ValueError:\n raise Exception('Inappropriate direction given')\n\n # --- Get the total number of cells along the direction\n hivects, ngrow = self._gethivects()\n nn = hivects[idir,:].max() - ngrow[idir] + self.overlaps[idir]\n if npes > 1:\n nn = comm_world.allreduce(nn, op=mpi.MAX)\n\n # --- Cell size in the direction\n dd = _libwarpx.getCellSize(celldir, self.level)\n\n # --- Get the nodal flag along direction\n nodal_flag = self.get_nodal_flag()[idir]\n\n # --- The centering shift\n if nodal_flag == 1:\n # node centered\n shift = 0.\n else:\n # cell centered\n shift = 0.5*dd\n\n return np.arange(nn)*dd + shift\n\n def __getitem__(self, index):\n \"\"\"Returns slices of a decomposed array, The shape of\n the object returned depends on the number of ix, iy and iz specified, which\n can be from none to all three. Note that the values of ix, iy and iz are\n relative to the fortran indexing, meaning that 0 is the lower boundary\n of the whole domain.\n \"\"\"\n if index == Ellipsis:\n index = tuple(self.dim*[slice(None)])\n\n if len(index) < self.dim:\n # --- Add extra dims to index if needed\n index = list(index)\n for i in range(len(index), self.dim):\n index.append(slice(None))\n index = tuple(index)\n\n if self.dim == 2:\n return self._getitem2d(index)\n elif self.dim == 3:\n return self._getitem3d(index)\n\n def _getitem3d(self, index):\n \"\"\"Returns slices of a 3D decomposed array,\n \"\"\"\n\n lovects, ngrow = self._getlovects()\n hivects, ngrow = self._gethivects()\n fields = self._getfields()\n\n ix = index[0]\n iy = index[1]\n iz = index[2]\n\n if len(fields[0].shape) > self.dim:\n ncomps = fields[0].shape[-1]\n else:\n ncomps = 1\n\n if len(index) > self.dim:\n if ncomps > 1:\n ic = index[-1]\n else:\n raise Exception('Too many indices given')\n else:\n ic = None\n\n nx = hivects[0,:].max() - ngrow[0]\n ny = hivects[1,:].max() - ngrow[1]\n nz = hivects[2,:].max() - ngrow[2]\n\n if npes > 1:\n nx = comm_world.allreduce(nx, op=mpi.MAX)\n ny = comm_world.allreduce(ny, op=mpi.MAX)\n nz = comm_world.allreduce(nz, op=mpi.MAX)\n\n if isinstance(ix, slice):\n ixstart = max(ix.start or -ngrow[0], -ngrow[0])\n ixstop = min(ix.stop or nx + 1 + ngrow[0], nx + self.overlaps[0] + ngrow[0])\n else:\n ixstart = ix\n ixstop = ix + 1\n if isinstance(iy, slice):\n iystart = max(iy.start or -ngrow[1], -ngrow[1])\n iystop = min(iy.stop or ny + 1 + ngrow[1], ny + self.overlaps[1] + ngrow[1])\n else:\n iystart = iy\n iystop = iy + 1\n if isinstance(iz, slice):\n izstart = max(iz.start or -ngrow[2], -ngrow[2])\n izstop = min(iz.stop or nz + 1 + ngrow[2], nz + self.overlaps[2] + ngrow[2])\n else:\n izstart = iz\n izstop = iz + 1\n\n # --- Setup the size of the array to be returned and create it.\n # --- Space is added for multiple components if needed.\n sss = (max(0, ixstop - ixstart),\n max(0, iystop - iystart),\n max(0, izstop - izstart))\n if ncomps > 1 and ic is None:\n sss = tuple(list(sss) + [ncomps])\n resultglobal = np.zeros(sss, dtype=_libwarpx._numpy_real_dtype)\n\n datalist = []\n for i in range(len(fields)):\n\n # --- The ix1, 2 etc are relative to global indexing\n ix1 = max(ixstart, lovects[0,i])\n ix2 = min(ixstop, lovects[0,i] + fields[i].shape[0])\n iy1 = max(iystart, lovects[1,i])\n iy2 = min(iystop, lovects[1,i] + fields[i].shape[1])\n iz1 = max(izstart, lovects[2,i])\n iz2 = min(izstop, lovects[2,i] + fields[i].shape[2])\n\n if ix1 < ix2 and iy1 < iy2 and iz1 < iz2:\n\n sss = (slice(ix1 - lovects[0,i], ix2 - lovects[0,i]),\n slice(iy1 - lovects[1,i], iy2 - lovects[1,i]),\n slice(iz1 - lovects[2,i], iz2 - lovects[2,i]))\n if ic is not None:\n sss = tuple(list(sss) + [ic])\n\n vslice = (slice(ix1 - ixstart, ix2 - ixstart),\n slice(iy1 - iystart, iy2 - iystart),\n slice(iz1 - izstart, iz2 - izstart))\n\n datalist.append((vslice, fields[i][sss]))\n\n if npes == 1:\n all_datalist = [datalist]\n else:\n all_datalist = comm_world.allgather(datalist)\n\n for datalist in all_datalist:\n for vslice, ff in datalist:\n resultglobal[vslice] = ff\n\n # --- Now remove any of the reduced dimensions.\n sss = [slice(None), slice(None), slice(None)]\n if not isinstance(ix, slice):\n sss[0] = 0\n if not isinstance(iy, slice):\n sss[1] = 0\n if not isinstance(iz, slice):\n sss[2] = 0\n\n return resultglobal[tuple(sss)]\n\n def _getitem2d(self, index):\n \"\"\"Returns slices of a 2D decomposed array,\n \"\"\"\n\n lovects, ngrow = self._getlovects()\n hivects, ngrow = self._gethivects()\n fields = self._getfields()\n\n ix = index[0]\n iz = index[1]\n\n if len(fields[0].shape) > self.dim:\n ncomps = fields[0].shape[-1]\n else:\n ncomps = 1\n\n if len(index) > self.dim:\n if ncomps > 1:\n ic = index[2]\n else:\n raise Exception('Too many indices given')\n else:\n ic = None\n\n nx = hivects[0,:].max() - ngrow[0]\n nz = hivects[1,:].max() - ngrow[1]\n\n if npes > 1:\n nx = comm_world.allreduce(nx, op=mpi.MAX)\n nz = comm_world.allreduce(nz, op=mpi.MAX)\n\n if isinstance(ix, slice):\n ixstart = max(ix.start or -ngrow[0], -ngrow[0])\n ixstop = min(ix.stop or nx + 1 + ngrow[0], nx + self.overlaps[0] + ngrow[0])\n else:\n ixstart = ix\n ixstop = ix + 1\n if isinstance(iz, slice):\n izstart = max(iz.start or -ngrow[1], -ngrow[1])\n izstop = min(iz.stop or nz + 1 + ngrow[1], nz + self.overlaps[1] + ngrow[1])\n else:\n izstart = iz\n izstop = iz + 1\n\n # --- Setup the size of the array to be returned and create it.\n # --- Space is added for multiple components if needed.\n sss = (max(0, ixstop - ixstart),\n max(0, izstop - izstart))\n if ncomps > 1 and ic is None:\n sss = tuple(list(sss) + [ncomps])\n resultglobal = np.zeros(sss, dtype=_libwarpx._numpy_real_dtype)\n\n datalist = []\n for i in range(len(fields)):\n\n # --- The ix1, 2 etc are relative to global indexing\n ix1 = max(ixstart, lovects[0,i])\n ix2 = min(ixstop, lovects[0,i] + fields[i].shape[0])\n iz1 = max(izstart, lovects[1,i])\n iz2 = min(izstop, lovects[1,i] + fields[i].shape[1])\n\n if ix1 < ix2 and iz1 < iz2:\n\n sss = (slice(ix1 - lovects[0,i], ix2 - lovects[0,i]),\n slice(iz1 - lovects[1,i], iz2 - lovects[1,i]))\n if ic is not None:\n sss = tuple(list(sss) + [ic])\n\n vslice = (slice(ix1 - ixstart, ix2 - ixstart),\n slice(iz1 - izstart, iz2 - izstart))\n\n datalist.append((vslice, fields[i][sss]))\n\n if npes == 1:\n all_datalist = [datalist]\n else:\n all_datalist = comm_world.allgather(datalist)\n\n for datalist in all_datalist:\n for vslice, ff in datalist:\n resultglobal[vslice] = ff\n\n # --- Now remove any of the reduced dimensions.\n sss = [slice(None), slice(None)]\n if not isinstance(ix, slice):\n sss[0] = 0\n if not isinstance(iz, slice):\n sss[1] = 0\n\n return resultglobal[tuple(sss)]\n\n def __setitem__(self, index, value):\n \"\"\"Sets slices of a decomposed array. The shape of\n the input object depends on the number of arguments specified, which can\n be from none to all three.\n - value: input array (must be supplied)\n \"\"\"\n if index == Ellipsis:\n index = tuple(self.dim*[slice(None)])\n\n if len(index) < self.dim:\n # --- Add extra dims to index if needed\n index = list(index)\n for i in range(len(index), self.dim):\n index.append(slice(None))\n index = tuple(index)\n\n if self.dim == 2:\n return self._setitem2d(index, value)\n elif self.dim == 3:\n return self._setitem3d(index, value)\n\n def _setitem3d(self, index, value):\n \"\"\"Sets slices of a decomposed 3D array.\n \"\"\"\n ix = index[0]\n iy = index[1]\n iz = index[2]\n\n lovects, ngrow = self._getlovects()\n hivects, ngrow = self._gethivects()\n fields = self._getfields()\n\n if len(index) > self.dim:\n if ncomps > 1:\n ic = index[-1]\n else:\n raise Exception('Too many indices given')\n else:\n ic = None\n\n nx = hivects[0,:].max() - ngrow[0]\n ny = hivects[1,:].max() - ngrow[1]\n nz = hivects[2,:].max() - ngrow[2]\n\n # --- Add extra dimensions so that the input has the same number of\n # --- dimensions as array.\n if isinstance(value, np.ndarray):\n value3d = np.array(value, copy=False)\n sss = list(value3d.shape)\n if not isinstance(ix, slice): sss[0:0] = [1]\n if not isinstance(iy, slice): sss[1:1] = [1]\n if not isinstance(iz, slice): sss[2:2] = [1]\n value3d.shape = sss\n\n if isinstance(ix, slice):\n ixstart = max(ix.start or -ngrow[0], -ngrow[0])\n ixstop = min(ix.stop or nx + 1 + ngrow[0], nx + self.overlaps[0] + ngrow[0])\n else:\n ixstart = ix\n ixstop = ix + 1\n if isinstance(iy, slice):\n iystart = max(iy.start or -ngrow[1], -ngrow[1])\n iystop = min(iy.stop or ny + 1 + ngrow[1], ny + self.overlaps[1] + ngrow[1])\n else:\n iystart = iy\n iystop = iy + 1\n if isinstance(iz, slice):\n izstart = max(iz.start or -ngrow[2], -ngrow[2])\n izstop = min(iz.stop or nz + 1 + ngrow[2], nz + self.overlaps[2] + ngrow[2])\n else:\n izstart = iz\n izstop = iz + 1\n\n for i in range(len(fields)):\n\n # --- The ix1, 2 etc are relative to global indexing\n ix1 = max(ixstart, lovects[0,i])\n ix2 = min(ixstop, lovects[0,i] + fields[i].shape[0])\n iy1 = max(iystart, lovects[1,i])\n iy2 = min(iystop, lovects[1,i] + fields[i].shape[1])\n iz1 = max(izstart, lovects[2,i])\n iz2 = min(izstop, lovects[2,i] + fields[i].shape[2])\n\n if ix1 < ix2 and iy1 < iy2 and iz1 < iz2:\n\n sss = (slice(ix1 - lovects[0,i], ix2 - lovects[0,i]),\n slice(iy1 - lovects[1,i], iy2 - lovects[1,i]),\n slice(iz1 - lovects[2,i], iz2 - lovects[2,i]))\n if ic is not None:\n sss = tuple(list(sss) + [ic])\n\n if isinstance(value, np.ndarray):\n vslice = (slice(ix1 - ixstart, ix2 - ixstart),\n slice(iy1 - iystart, iy2 - iystart),\n slice(iz1 - izstart, iz2 - izstart))\n fields[i][sss] = value3d[vslice]\n else:\n fields[i][sss] = value\n\n def _setitem2d(self, index, value):\n \"\"\"Sets slices of a decomposed 2D array.\n \"\"\"\n ix = index[0]\n iz = index[2]\n\n lovects, ngrow = self._getlovects()\n hivects, ngrow = self._gethivects()\n fields = self._getfields()\n\n if len(fields[0].shape) > self.dim:\n ncomps = fields[0].shape[-1]\n else:\n ncomps = 1\n\n if len(index) > self.dim:\n if ncomps > 1:\n ic = index[2]\n else:\n raise Exception('Too many indices given')\n else:\n ic = None\n\n nx = hivects[0,:].max() - ngrow[0]\n nz = hivects[2,:].max() - ngrow[1]\n\n # --- Add extra dimensions so that the input has the same number of\n # --- dimensions as array.\n if isinstance(value, np.ndarray):\n value3d = np.array(value, copy=False)\n sss = list(value3d.shape)\n if not isinstance(ix, slice): sss[0:0] = [1]\n if not isinstance(iz, slice): sss[1:1] = [1]\n value3d.shape = sss\n\n if isinstance(ix, slice):\n ixstart = max(ix.start or -ngrow[0], -ngrow[0])\n ixstop = min(ix.stop or nx + 1 + ngrow[0], nx + self.overlaps[0] + ngrow[0])\n else:\n ixstart = ix\n ixstop = ix + 1\n if isinstance(iz, slice):\n izstart = max(iz.start or -ngrow[1], -ngrow[1])\n izstop = min(iz.stop or nz + 1 + ngrow[1], nz + self.overlaps[2] + ngrow[1])\n else:\n izstart = iz\n izstop = iz + 1\n\n for i in range(len(fields)):\n\n # --- The ix1, 2 etc are relative to global indexing\n ix1 = max(ixstart, lovects[0,i])\n ix2 = min(ixstop, lovects[0,i] + fields[i].shape[0])\n iz1 = max(izstart, lovects[2,i])\n iz2 = min(izstop, lovects[2,i] + fields[i].shape[2])\n\n if ix1 < ix2 and iz1 < iz2:\n\n sss = (slice(ix1 - lovects[0,i], ix2 - lovects[0,i]),\n slice(iz1 - lovects[2,i], iz2 - lovects[2,i]))\n if ic is not None:\n sss = tuple(list(sss) + [ic])\n\n if isinstance(value, np.ndarray):\n vslice = (slice(ix1 - ixstart, ix2 - ixstart),\n slice(iz1 - izstart, iz2 - izstart))\n fields[i][sss] = value3d[vslice]\n else:\n fields[i][sss] = value\n\n\ndef ExWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_electric_field_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field,\n get_nodal_flag=_libwarpx.get_Ex_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EyWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_electric_field_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field,\n get_nodal_flag=_libwarpx.get_Ey_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EzWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_electric_field_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field,\n get_nodal_flag=_libwarpx.get_Ez_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BxWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_magnetic_field_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field,\n get_nodal_flag=_libwarpx.get_Bx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ByWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_magnetic_field_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field,\n get_nodal_flag=_libwarpx.get_By_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BzWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_magnetic_field_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field,\n get_nodal_flag=_libwarpx.get_Bz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JxWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_current_density_lovects,\n get_fabs=_libwarpx.get_mesh_current_density,\n get_nodal_flag=_libwarpx.get_Jx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JyWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_current_density_lovects,\n get_fabs=_libwarpx.get_mesh_current_density,\n get_nodal_flag=_libwarpx.get_Jy_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JzWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_current_density_lovects,\n get_fabs=_libwarpx.get_mesh_current_density,\n get_nodal_flag=_libwarpx.get_Jz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ExCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_electric_field_cp_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field_cp,\n get_nodal_flag=_libwarpx.get_Ex_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EyCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_electric_field_cp_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field_cp,\n get_nodal_flag=_libwarpx.get_Ey_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EzCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_electric_field_cp_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field_cp,\n get_nodal_flag=_libwarpx.get_Ez_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BxCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_magnetic_field_cp_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field_cp,\n get_nodal_flag=_libwarpx.get_Bx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ByCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_magnetic_field_cp_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field_cp,\n get_nodal_flag=_libwarpx.get_By_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BzCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_magnetic_field_cp_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field_cp,\n get_nodal_flag=_libwarpx.get_Bz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JxCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_current_density_cp_lovects,\n get_fabs=_libwarpx.get_mesh_current_density_cp,\n get_nodal_flag=_libwarpx.get_Jx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JyCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_current_density_cp_lovects,\n get_fabs=_libwarpx.get_mesh_current_density_cp,\n get_nodal_flag=_libwarpx.get_Jy_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JzCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_current_density_cp_lovects,\n get_fabs=_libwarpx.get_mesh_current_density_cp,\n get_nodal_flag=_libwarpx.get_Jz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef RhoCPWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=None,\n get_lovects=_libwarpx.get_mesh_charge_density_cp_lovects,\n get_fabs=_libwarpx.get_mesh_charge_density_cp,\n get_nodal_flag=_libwarpx.get_Rho_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ExFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_electric_field_fp_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field_fp,\n get_nodal_flag=_libwarpx.get_Ex_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EyFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_electric_field_fp_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field_fp,\n get_nodal_flag=_libwarpx.get_Ey_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EzFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_electric_field_fp_lovects,\n get_fabs=_libwarpx.get_mesh_electric_field_fp,\n get_nodal_flag=_libwarpx.get_Ez_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BxFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_magnetic_field_fp_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field_fp,\n get_nodal_flag=_libwarpx.get_Bx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ByFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_magnetic_field_fp_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field_fp,\n get_nodal_flag=_libwarpx.get_By_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BzFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_magnetic_field_fp_lovects,\n get_fabs=_libwarpx.get_mesh_magnetic_field_fp,\n get_nodal_flag=_libwarpx.get_Bz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JxFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_current_density_fp_lovects,\n get_fabs=_libwarpx.get_mesh_current_density_fp,\n get_nodal_flag=_libwarpx.get_Jx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JyFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_current_density_fp_lovects,\n get_fabs=_libwarpx.get_mesh_current_density_fp,\n get_nodal_flag=_libwarpx.get_Jy_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JzFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_current_density_fp_lovects,\n get_fabs=_libwarpx.get_mesh_current_density_fp,\n get_nodal_flag=_libwarpx.get_Jz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef RhoFPWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=None,\n get_lovects=_libwarpx.get_mesh_charge_density_fp_lovects,\n get_fabs=_libwarpx.get_mesh_charge_density_fp,\n get_nodal_flag=_libwarpx.get_Rho_nodal_flag,\n level=level, include_ghosts=include_ghosts)\ndef ExCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_electric_field_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_electric_field_cp_pml,\n get_nodal_flag=_libwarpx.get_Ex_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EyCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_electric_field_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_electric_field_cp_pml,\n get_nodal_flag=_libwarpx.get_Ey_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EzCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_electric_field_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_electric_field_cp_pml,\n get_nodal_flag=_libwarpx.get_Ez_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BxCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_magnetic_field_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_magnetic_field_cp_pml,\n get_nodal_flag=_libwarpx.get_Bx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ByCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_magnetic_field_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_magnetic_field_cp_pml,\n get_nodal_flag=_libwarpx.get_By_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BzCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_magnetic_field_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_magnetic_field_cp_pml,\n get_nodal_flag=_libwarpx.get_Bz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JxCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_current_density_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_current_density_cp_pml,\n get_nodal_flag=_libwarpx.get_Jx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JyCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_current_density_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_current_density_cp_pml,\n get_nodal_flag=_libwarpx.get_Jy_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JzCPPMLWrapper(level=1, include_ghosts=False):\n assert level>0, Exception('Coarse patch only available on levels > 0')\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_current_density_cp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_current_density_cp_pml,\n get_nodal_flag=_libwarpx.get_Jz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ExFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_electric_field_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_electric_field_fp_pml,\n get_nodal_flag=_libwarpx.get_Ex_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EyFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_electric_field_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_electric_field_fp_pml,\n get_nodal_flag=_libwarpx.get_Ey_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef EzFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_electric_field_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_electric_field_fp_pml,\n get_nodal_flag=_libwarpx.get_Ez_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BxFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_magnetic_field_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_magnetic_field_fp_pml,\n get_nodal_flag=_libwarpx.get_Bx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef ByFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_magnetic_field_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_magnetic_field_fp_pml,\n get_nodal_flag=_libwarpx.get_By_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef BzFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_magnetic_field_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_magnetic_field_fp_pml,\n get_nodal_flag=_libwarpx.get_Bz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JxFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=0,\n get_lovects=_libwarpx.get_mesh_current_density_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_current_density_fp_pml,\n get_nodal_flag=_libwarpx.get_Jx_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JyFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=1,\n get_lovects=_libwarpx.get_mesh_current_density_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_current_density_fp_pml,\n get_nodal_flag=_libwarpx.get_Jy_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n\ndef JzFPPMLWrapper(level=0, include_ghosts=False):\n return _MultiFABWrapper(direction=2,\n get_lovects=_libwarpx.get_mesh_current_density_fp_lovects_pml,\n get_fabs=_libwarpx.get_mesh_current_density_fp_pml,\n get_nodal_flag=_libwarpx.get_Jz_nodal_flag,\n level=level, include_ghosts=include_ghosts)\n" ]
[ [ "numpy.arange", "numpy.array", "numpy.zeros_like", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
brianwa84/probability
[ "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e", "6f8e78d859ac41170be5147c8c7bde54cc5aa83e" ]
[ "tensorflow_probability/python/distributions/skellam_test.py", "tensorflow_probability/python/distributions/lognormal_test.py", "tensorflow_probability/python/internal/tensor_util.py", "spinoffs/inference_gym/inference_gym/targets/vector_model.py", "spinoffs/oryx/oryx/util/summary_test.py", "spinoffs/inference_gym/inference_gym/targets/non_identifiable_quartic.py", "tensorflow_probability/python/bijectors/kumaraswamy_cdf.py", "tensorflow_probability/python/experimental/nn/util/convolution_util.py", "spinoffs/inference_gym/inference_gym/targets/ground_truth/german_credit_numeric_logistic_regression.py", "tensorflow_probability/python/distributions/lkj_test.py", "tensorflow_probability/python/bijectors/rational_quadratic_spline_test.py", "tensorflow_probability/python/math/bessel_test.py", "tensorflow_probability/python/distributions/batch_broadcast.py", "tensorflow_probability/python/internal/special_math_test.py", "tensorflow_probability/python/distributions/poisson_test.py", "tensorflow_probability/python/distributions/pert.py", "tensorflow_probability/python/math/hypergeometric_test.py", "tensorflow_probability/python/experimental/distribute/sharded.py" ]
[ "# Copyright 2018 The TensorFlow Probability 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# ============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nimport numpy as np\nfrom scipy import stats\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\n\nfrom tensorflow_probability.python.internal import test_util\ntfd = tfp.distributions\n\n\n@test_util.test_all_tf_execution_regimes\nclass _SkellamTest(object):\n\n def _make_skellam(self,\n rate1,\n rate2,\n validate_args=True,\n force_probs_to_zero_outside_support=False):\n return tfd.Skellam(\n rate1=rate1,\n rate2=rate2,\n validate_args=validate_args,\n force_probs_to_zero_outside_support=force_probs_to_zero_outside_support)\n\n def testSkellamShape(self):\n rate1 = tf.constant([3.0] * 5, dtype=self.dtype)\n rate2 = tf.constant([3.0] * 4, dtype=self.dtype)[..., tf.newaxis]\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n\n self.assertAllEqual(self.evaluate(skellam.batch_shape_tensor()), (4, 5))\n self.assertEqual(skellam.batch_shape, tf.TensorShape([4, 5]))\n self.assertAllEqual(self.evaluate(skellam.event_shape_tensor()), [])\n self.assertEqual(skellam.event_shape, tf.TensorShape([]))\n\n def testInvalidLam(self):\n invalid_rate = self.dtype([-.01, 1., 2.])\n valid_rate = self.dtype([1., 2., 3.])\n with self.assertRaisesOpError('Argument `rate1` must be non-negative.'):\n skellam = self._make_skellam(rate1=invalid_rate, rate2=valid_rate)\n self.evaluate(skellam.rate1_parameter())\n\n with self.assertRaisesOpError('Argument `rate2` must be non-negative.'):\n skellam = self._make_skellam(rate1=valid_rate, rate2=invalid_rate)\n self.evaluate(skellam.rate2_parameter())\n\n def testZeroRate(self):\n lam = self.dtype(0.)\n skellam = tfd.Skellam(rate1=lam, rate2=lam, validate_args=True)\n self.assertAllClose(lam, self.evaluate(skellam.rate1))\n self.assertAllClose(lam, self.evaluate(skellam.rate2))\n self.assertAllClose(0., skellam.prob(3.))\n self.assertAllClose(1., skellam.prob(0.))\n self.assertAllClose(0., skellam.log_prob(0.))\n\n def testSkellamLogPmfDiscreteMatchesScipy(self):\n batch_size = 12\n rate1 = np.linspace(1, 12, 12).astype(self.dtype)\n rate2 = np.array([[1.2], [2.3]]).astype(self.dtype)\n x = np.array([-3., -1., 0., 2., 4., 3., 7., 4., 8., 9., 6., 7.],\n dtype=self.dtype)\n skellam = self._make_skellam(\n rate1=rate1, rate2=rate2,\n force_probs_to_zero_outside_support=True, validate_args=False)\n log_pmf = skellam.log_prob(x)\n self.assertEqual(log_pmf.shape, (2, batch_size))\n self.assertAllClose(\n self.evaluate(log_pmf),\n stats.skellam.logpmf(x, rate1, rate2))\n\n pmf = skellam.prob(x)\n self.assertEqual(pmf.shape, (2, batch_size,))\n self.assertAllClose(\n self.evaluate(pmf),\n stats.skellam.pmf(x, rate1, rate2))\n\n @test_util.numpy_disable_gradient_test\n def testSkellamLogPmfGradient(self):\n batch_size = 6\n rate1 = tf.constant([3.] * batch_size, dtype=self.dtype)\n rate2 = tf.constant([2.7] * batch_size, dtype=self.dtype)\n x = np.array([-1., 2., 3., 4., 5., 6.], dtype=self.dtype)\n\n err = self.compute_max_gradient_error(\n lambda lam: self._make_skellam( # pylint:disable=g-long-lambda\n rate1=lam, rate2=rate2).log_prob(x), [rate1])\n self.assertLess(err, 7e-4)\n\n err = self.compute_max_gradient_error(\n lambda lam: self._make_skellam( # pylint:disable=g-long-lambda\n rate1=rate1, rate2=lam).log_prob(x), [rate2])\n self.assertLess(err, 7e-4)\n\n @test_util.numpy_disable_gradient_test\n def testSkellamLogPmfGradientAtZeroPmf(self):\n # Check that the derivative wrt parameter at the zero-prob points is zero.\n batch_size = 6\n rate1 = tf.constant(np.linspace(1, 7, 6), dtype=self.dtype)\n rate2 = tf.constant(np.linspace(9.1, 12.1, 6), dtype=self.dtype)\n x = tf.constant([-2.1, -1.3, -0.5, 0.2, 1.5, 10.5], dtype=self.dtype)\n\n def make_skellam_log_prob(apply_to_second_rate=False):\n def skellam_log_prob(lam):\n return self._make_skellam(\n rate1=rate1 if apply_to_second_rate else lam,\n rate2=lam if apply_to_second_rate else rate2,\n force_probs_to_zero_outside_support=True,\n validate_args=False).log_prob(x)\n return skellam_log_prob\n _, dlog_pmf_dlam = self.evaluate(tfp.math.value_and_gradient(\n make_skellam_log_prob(), rate1))\n\n self.assertEqual(dlog_pmf_dlam.shape, (batch_size,))\n self.assertAllClose(dlog_pmf_dlam, np.zeros([batch_size]))\n\n _, dlog_pmf_dlam = self.evaluate(tfp.math.value_and_gradient(\n make_skellam_log_prob(True), rate2))\n\n self.assertEqual(dlog_pmf_dlam.shape, (batch_size,))\n self.assertAllClose(dlog_pmf_dlam, np.zeros([batch_size]))\n\n def testSkellamMean(self):\n rate1 = np.array([1.0, 3.0, 2.5], dtype=self.dtype)\n rate2 = np.array([5.0, 7.13, 2.56, 41.], dtype=self.dtype)[..., np.newaxis]\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n self.assertEqual(skellam.mean().shape, (4, 3))\n self.assertAllClose(\n self.evaluate(skellam.mean()), stats.skellam.mean(rate1, rate2))\n self.assertAllClose(self.evaluate(skellam.mean()), rate1 - rate2)\n\n def testSkellamVariance(self):\n rate1 = np.array([1.0, 3.0, 2.5], dtype=self.dtype)\n rate2 = np.array([5.0, 7.13, 2.56, 41.], dtype=self.dtype)[..., np.newaxis]\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n self.assertEqual(skellam.variance().shape, (4, 3))\n self.assertAllClose(\n self.evaluate(skellam.variance()), stats.skellam.var(rate1, rate2))\n self.assertAllClose(self.evaluate(skellam.variance()), rate1 + rate2)\n\n def testSkellamStd(self):\n rate1 = np.array([1.0, 3.0, 2.5], dtype=self.dtype)\n rate2 = np.array([5.0, 7.13, 2.56, 41.], dtype=self.dtype)[..., np.newaxis]\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n self.assertEqual(skellam.stddev().shape, (4, 3))\n self.assertAllClose(\n self.evaluate(skellam.stddev()), stats.skellam.std(rate1, rate2))\n self.assertAllClose(self.evaluate(skellam.stddev()), np.sqrt(rate1 + rate2))\n\n def testSkellamSample(self):\n rate1 = self.dtype([2., 3., 4.])\n rate2 = self.dtype([7.1, 3.2])[..., np.newaxis]\n n = int(2e5)\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n samples = skellam.sample(n, seed=test_util.test_seed())\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n, 2, 3))\n self.assertEqual(sample_values.shape, (n, 2, 3))\n self.assertAllClose(\n sample_values.mean(axis=0), stats.skellam.mean(rate1, rate2), rtol=.03)\n self.assertAllClose(\n sample_values.var(axis=0), stats.skellam.var(rate1, rate2), rtol=.03)\n\n def testAssertValidSample(self):\n rate1 = np.array([1.0, 3.0, 2.5], dtype=self.dtype)\n rate2 = np.array([2.1, 7.0, 42.5], dtype=self.dtype)\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n with self.assertRaisesOpError('has non-integer components'):\n self.evaluate(skellam.prob([-1.2, 3., 4.2]))\n\n def testSkellamSampleMultidimensionalMean(self):\n rate1 = self.dtype([2., 3., 4., 5., 6.])\n rate2 = self.dtype([7.1, 3.2, 10., 9.])[..., np.newaxis]\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n n = int(2e5)\n samples = skellam.sample(n, seed=test_util.test_seed())\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n, 4, 5))\n self.assertEqual(sample_values.shape, (n, 4, 5))\n self.assertAllClose(\n sample_values.mean(axis=0),\n stats.skellam.mean(rate1, rate2), rtol=.04, atol=0)\n\n def testSkellamSampleMultidimensionalVariance(self):\n rate1 = self.dtype([2., 3., 4., 5., 6.])\n rate2 = self.dtype([7.1, 3.2, 10., 9.])[..., np.newaxis]\n skellam = self._make_skellam(rate1=rate1, rate2=rate2)\n n = int(1e5)\n samples = skellam.sample(n, seed=test_util.test_seed())\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n, 4, 5))\n self.assertEqual(sample_values.shape, (n, 4, 5))\n\n self.assertAllClose(\n sample_values.var(axis=0),\n stats.skellam.var(rate1, rate2), rtol=.03, atol=0)\n\n @test_util.tf_tape_safety_test\n def testGradientThroughRate(self):\n rate1 = tf.Variable(3.)\n rate2 = tf.Variable(4.)\n dist = self._make_skellam(rate1=rate1, rate2=rate2)\n with tf.GradientTape() as tape:\n loss = -dist.log_prob([1., 2., 4.])\n grad = tape.gradient(loss, dist.trainable_variables)\n self.assertLen(grad, 2)\n self.assertAllNotNone(grad)\n\n def testAssertsNonNegativeRate(self):\n rate1 = tf.Variable([-1., 2., -3.])\n rate2 = tf.Variable([1., 2., 3.])\n self.evaluate([rate1.initializer, rate2.initializer])\n with self.assertRaisesOpError('Argument `rate1` must be non-negative.'):\n dist = self._make_skellam(\n rate1=rate1, rate2=rate2, validate_args=True)\n self.evaluate(dist.sample(seed=test_util.test_seed()))\n\n rate1 = tf.Variable([1., 2., 3.])\n rate2 = tf.Variable([-1., 2., -3.])\n self.evaluate([rate1.initializer, rate2.initializer])\n\n with self.assertRaisesOpError('Argument `rate2` must be non-negative.'):\n dist = self._make_skellam(\n rate1=rate1, rate2=rate2, validate_args=True)\n self.evaluate(dist.sample(seed=test_util.test_seed()))\n\n def testAssertsNonNegativeRateAfterMutation(self):\n rate1 = tf.Variable([1., 2., 3.])\n rate2 = tf.Variable([1., 2., 3.])\n self.evaluate([rate1.initializer, rate2.initializer])\n dist = self._make_skellam(\n rate1=rate1, rate2=rate2, validate_args=True)\n self.evaluate(dist.mean())\n with self.assertRaisesOpError('Argument `rate1` must be non-negative.'):\n with tf.control_dependencies([rate1.assign([1., 2., -3.])]):\n self.evaluate(dist.sample(seed=test_util.test_seed()))\n\n rate1 = tf.Variable([1., 2., 3.])\n rate2 = tf.Variable([1., 2., 3.])\n self.evaluate([rate1.initializer, rate2.initializer])\n dist = self._make_skellam(\n rate1=rate1, rate2=rate2, validate_args=True)\n self.evaluate(dist.mean())\n\n with self.assertRaisesOpError('Argument `rate2` must be non-negative.'):\n with tf.control_dependencies([rate2.assign([1., 2., -3.])]):\n self.evaluate(dist.sample(seed=test_util.test_seed()))\n\n\n@test_util.test_all_tf_execution_regimes\nclass SkellamTestFloat32(test_util.TestCase, _SkellamTest):\n dtype = np.float32\n\n\n@test_util.test_all_tf_execution_regimes\nclass SkellamTestFloat64(test_util.TestCase, _SkellamTest):\n dtype = np.float64\n\n\n@test_util.test_all_tf_execution_regimes\nclass SkellamLogRateTest(_SkellamTest):\n\n def _make_skellam(self,\n rate1,\n rate2,\n validate_args=True,\n force_probs_to_zero_outside_support=False):\n return tfd.Skellam(\n log_rate1=tf.math.log(rate1),\n log_rate2=tf.math.log(rate2),\n validate_args=validate_args,\n force_probs_to_zero_outside_support=force_probs_to_zero_outside_support)\n\n # No need to worry about the non-negativity of `rate` when using the\n # `log_rate` parameterization.\n def testInvalidLam(self):\n pass\n\n def testAssertsNonNegativeRate(self):\n pass\n\n def testAssertsNonNegativeRateAfterMutation(self):\n pass\n\n # The gradient is not tracked through tf.math.log(rate) in _make_skellam(),\n # so log_rate needs to be defined as a Variable and passed directly.\n @test_util.tf_tape_safety_test\n def testGradientThroughRate(self):\n log_rate1 = tf.Variable(3.)\n log_rate2 = tf.Variable(4.)\n dist = tfd.Skellam(\n log_rate1=log_rate1, log_rate2=log_rate2, validate_args=True)\n with tf.GradientTape() as tape:\n loss = -dist.log_prob([1., 2., 4.])\n grad = tape.gradient(loss, dist.trainable_variables)\n self.assertLen(grad, 2)\n self.assertAllNotNone(grad)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for LogNormal.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_probability.python import distributions as tfd\nfrom tensorflow_probability.python.internal import test_util\n\n\n@test_util.test_all_tf_execution_regimes\nclass LogNormalTest(test_util.TestCase):\n\n def setUp(self):\n self._rng = np.random.RandomState(123)\n\n def testLogNormalStats(self):\n\n loc = np.float32([3., 1.5])\n scale = np.float32([0.4, 1.1])\n dist = tfd.LogNormal(loc=loc, scale=scale, validate_args=True)\n\n self.assertAllClose(self.evaluate(dist.mean()),\n np.exp(loc + scale**2 / 2))\n self.assertAllClose(self.evaluate(dist.variance()),\n (np.exp(scale**2) - 1) * np.exp(2 * loc + scale**2))\n self.assertAllClose(self.evaluate(dist.stddev()),\n np.sqrt(self.evaluate(dist.variance())))\n self.assertAllClose(self.evaluate(dist.mode()),\n np.exp(loc - scale**2))\n self.assertAllClose(self.evaluate(dist.entropy()),\n np.log(scale * np.exp(loc + 0.5) * np.sqrt(2 * np.pi)))\n\n def testLogNormalSample(self):\n loc, scale = 1.5, 0.4\n dist = tfd.LogNormal(loc=loc, scale=scale, validate_args=True)\n samples = self.evaluate(dist.sample(6000, seed=test_util.test_seed()))\n self.assertAllClose(np.mean(samples),\n self.evaluate(dist.mean()),\n atol=0.1)\n self.assertAllClose(np.std(samples),\n self.evaluate(dist.stddev()),\n atol=0.1)\n\n def testLogNormalPDF(self):\n loc, scale = 1.5, 0.4\n dist = tfd.LogNormal(loc=loc, scale=scale, validate_args=True)\n\n x = np.array([1e-4, 1.0, 2.0], dtype=np.float32)\n\n log_pdf = dist.log_prob(x)\n analytical_log_pdf = -np.log(x * scale * np.sqrt(2 * np.pi)) - (\n np.log(x) - loc)**2 / (2. * scale**2)\n\n self.assertAllClose(self.evaluate(log_pdf), analytical_log_pdf)\n\n def testLogNormalCDF(self):\n loc, scale = 1.5, 0.4\n dist = tfd.LogNormal(loc=loc, scale=scale, validate_args=True)\n\n x = np.array([1e-4, 1.0, 2.0], dtype=np.float32)\n\n cdf = dist.cdf(x)\n analytical_cdf = .5 + .5 * tf.math.erf(\n (np.log(x) - loc) / (scale * np.sqrt(2)))\n self.assertAllClose(self.evaluate(cdf),\n self.evaluate(analytical_cdf))\n\n def testLogNormalLogNormalKL(self):\n batch_size = 6\n mu_a = np.array([3.0] * batch_size)\n sigma_a = np.array([1.0, 2.0, 3.0, 1.5, 2.5, 3.5])\n mu_b = np.array([-3.0] * batch_size)\n sigma_b = np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0])\n\n ln_a = tfd.LogNormal(loc=mu_a, scale=sigma_a, validate_args=True)\n ln_b = tfd.LogNormal(loc=mu_b, scale=sigma_b, validate_args=True)\n\n kl = tfd.kl_divergence(ln_a, ln_b)\n kl_val = self.evaluate(kl)\n\n normal_a = tfd.Normal(loc=mu_a, scale=sigma_a, validate_args=True)\n normal_b = tfd.Normal(loc=mu_b, scale=sigma_b, validate_args=True)\n kl_expected_from_normal = tfd.kl_divergence(normal_a, normal_b)\n\n kl_expected_from_formula = ((mu_a - mu_b)**2 / (2 * sigma_b**2) + 0.5 * (\n (sigma_a**2 / sigma_b**2) - 1 - 2 * np.log(sigma_a / sigma_b)))\n\n x = ln_a.sample(int(2e5), seed=test_util.test_seed())\n kl_sample = tf.reduce_mean(ln_a.log_prob(x) - ln_b.log_prob(x), axis=0)\n kl_sample_ = self.evaluate(kl_sample)\n\n self.assertEqual(kl.shape, (batch_size,))\n self.assertAllClose(kl_val, kl_expected_from_normal)\n self.assertAllClose(kl_val, kl_expected_from_formula)\n self.assertAllClose(\n kl_expected_from_formula, kl_sample_, atol=0.0, rtol=1e-2)\n\n # TODO(b/144948687) Avoid `nan` at boundary. Ideally we'd do this test:\n # def testPdfAtBoundary(self):\n # dist = tfd.LogNormal(loc=5., scale=2.)\n # pdf = self.evaluate(dist.prob(0.))\n # log_pdf = self.evaluate(dist.log_prob(0.))\n # self.assertEqual(pdf, 0.)\n # self.assertAllNegativeInf(log_pdf)\n\n def testAssertValidSample(self):\n dist = tfd.LogNormal(loc=[-3., 1., 4.], scale=2., validate_args=True)\n with self.assertRaisesOpError('Sample must be non-negative.'):\n self.evaluate(dist.cdf([3., -0.2, 1.]))\n\n def testSupportBijectorOutsideRange(self):\n dist = tfd.LogNormal(loc=1., scale=2., validate_args=True)\n with self.assertRaisesOpError('must be greater than or equal to 0'):\n dist.experimental_default_event_space_bijector().inverse(\n [-4.2, -1e-6, -1.3])\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tools for processing Tensors.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import prefer_static\n\n__all__ = [\n 'convert_nonref_to_tensor',\n 'discover_trainable_variables',\n 'discover_variables',\n 'is_module',\n 'is_ref',\n 'is_trainable_variable',\n 'is_variable',\n]\n\n\ndef convert_nonref_to_tensor(value, dtype=None, dtype_hint=None,\n as_shape_tensor=False, name=None):\n \"\"\"Converts the given `value` to a `Tensor` if input is nonreference type.\n\n This function converts Python objects of various types to `Tensor` objects\n only if the input has nonreference semantics. Reference semantics are\n characterized by `tensor_util.is_ref` and is any object which is a\n `tf.Variable` or instance of `tf.Module`. This function accepts any input\n which `tf.convert_to_tensor` would also.\n\n Note: This function diverges from default Numpy behavior for `float` and\n `string` types when `None` is present in a Python list or scalar. Rather\n than silently converting `None` values, an error will be thrown.\n\n Args:\n value: An object whose type has a registered `Tensor` conversion function.\n dtype: Optional element type for the returned tensor. If missing, the\n type is inferred from the type of `value`.\n dtype_hint: Optional element type for the returned tensor,\n used when dtype is None. In some cases, a caller may not have a\n dtype in mind when converting to a tensor, so dtype_hint\n can be used as a soft preference. If the conversion to\n `dtype_hint` is not possible, this argument has no effect.\n as_shape_tensor: Optional boolean when if `True` uses\n `prefer_static.convert_to_shape_tensor` instead of `tf.convert_to_tensor`\n for JAX compatibility.\n name: Optional name to use if a new `Tensor` is created.\n\n Returns:\n tensor: A `Tensor` based on `value`.\n\n Raises:\n TypeError: If no conversion function is registered for `value` to `dtype`.\n RuntimeError: If a registered conversion function returns an invalid value.\n ValueError: If the `value` is a tensor not of given `dtype` in graph mode.\n\n\n #### Examples:\n\n ```python\n from tensorflow_probability.python.internal import tensor_util\n\n x = tf.Variable(0.)\n y = tensor_util.convert_nonref_to_tensor(x)\n x is y\n # ==> True\n\n x = tf.constant(0.)\n y = tensor_util.convert_nonref_to_tensor(x)\n x is y\n # ==> True\n\n x = np.array(0.)\n y = tensor_util.convert_nonref_to_tensor(x)\n x is y\n # ==> False\n tf.is_tensor(y)\n # ==> True\n\n x = tfp.util.DeferredTensor(13.37, lambda x: x)\n y = tensor_util.convert_nonref_to_tensor(x)\n x is y\n # ==> True\n tf.is_tensor(y)\n # ==> True\n tf.equal(y, 13.37)\n # ==> True\n ```\n\n \"\"\"\n # We explicitly do not use a tf.name_scope to avoid graph clutter.\n if value is None:\n return None\n if is_ref(value):\n if dtype is None:\n return value\n dtype_base = dtype_util.base_dtype(dtype)\n value_dtype_base = dtype_util.base_dtype(value.dtype)\n if dtype_base != value_dtype_base:\n raise TypeError('Mutable type must be of dtype \"{}\" but is \"{}\".'.format(\n dtype_util.name(dtype_base), dtype_util.name(value_dtype_base)))\n return value\n if as_shape_tensor:\n return prefer_static.convert_to_shape_tensor(\n value, dtype=dtype, dtype_hint=dtype_hint, name=name)\n return tf.convert_to_tensor(\n value, dtype=dtype, dtype_hint=dtype_hint, name=name)\n\n\ndef is_ref(x):\n \"\"\"Evaluates if the object has reference semantics.\n\n An object is deemed \"reference\" if it is a `tf.Variable` instance or is\n derived from a `tf.Module` with `dtype` and `shape` properties.\n\n Args:\n x: Any object.\n\n Returns:\n is_ref: Python `bool` indicating input is has nonreference semantics, i.e.,\n is a `tf.Variable` or a `tf.Module` with `dtype` and `shape` properties.\n \"\"\"\n # TODO(b/134430874): Consider making this recurse through nests, e.g.,\n # `tensor_util.is_ref([tf.Variable(0.), np.array(1.)])`\n # returns True. Note: we'd need to actually create a tf.Module on user's\n # behalf and it would need a `dtype` and `shape`. (I.e., there would be some\n # work to support this.)\n return (\n is_variable(x) or\n (is_module(x) and hasattr(x, 'dtype') and hasattr(x, 'shape'))\n )\n\n\ndef is_variable(x):\n \"\"\"Returns `True` when input is a `tf.Variable`, otherwise `False`.\"\"\"\n return isinstance(x, tf.Variable)\n\n\ndef is_trainable_variable(x):\n \"\"\"Returns `True` when input is trainable `tf.Variable`, otherwise `False`.\"\"\"\n return is_variable(x) and getattr(x, 'trainable', False)\n\n\ndef is_module(x):\n \"\"\"Returns `True` when input is a `tf.Module`, otherwise `False`.\"\"\"\n return isinstance(x, tf.Module)\n\n\nclass _Track(tf.Module):\n \"\"\"Bridge to create functional interface for variable tracking.\"\"\"\n\n def __init__(self, *args, **kwargs):\n self._args = args\n self._kwargs = kwargs\n\n\ndef discover_trainable_variables(x):\n \"\"\"Returns `tuple` of all trainable `tf.Variables` discoverable in input.\n\n Warning: unlike possibly `tf.Module`, use of this function only does a static,\n \"one-time\" discovery. (This is self-evidently true from its functional\n nature.)\n\n Args:\n x: An object to inspected for `tf.Variable` dependencies.\n\n Returns:\n trainable_vars: A Python `tuple` of `tf.Variable`s with `trainable=True`.\n \"\"\"\n return _Track(x).trainable_variables\n\n\ndef discover_variables(x):\n \"\"\"Returns `tuple` of all `tf.Variables` discoverable in input.\n\n Warning: unlike possibly `tf.Module`, use of this function only does a static,\n \"one-time\" discovery. (This is self-evidently true from its functional\n nature.)\n\n Args:\n x: An object to inspected for `tf.Variable` dependencies.\n\n Returns:\n vars: A Python `tuple` of `tf.Variable`s, regardless of their value of\n `trainable`.\n \"\"\"\n return _Track(x).variables\n", "# Lint as: python3\n# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Implementation of the VectorModel.\"\"\"\n\nimport collections\nimport functools\n\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\n\nfrom tensorflow_probability.python.internal import prefer_static as ps\nfrom inference_gym.targets import model as model_lib\n\ntfb = tfp.bijectors\n\n__all__ = [\n 'VectorModel',\n]\n\n\nclass VectorModel(model_lib.Model):\n \"\"\"An adapter to convert an existing model to have a vector-valued support.\n\n This adapter makes it convenient to use the Inference Gym models with\n inference algorithms which cannot handle structured events. It does so by\n reshaping individual event Tensors and concatenating them into a single\n vector.\n\n The resultant vector-valued model has updated properties and sample\n transformations which reflect the transformation above. By default, the sample\n transformations will still return structured values. This behavior can be\n altered via the `flatten_sample_transformations` argument.\n\n There are only two restrictions on the models that can be handled by this\n class:\n\n 1. The individual Tensors in an event must all have the same dtype.\n 2. The `default_event_space_bijector` must apply to a single tensor at time.\n\n The second restriction will be lifted soon.\n\n #### Example\n\n ```\n base_model = gym.targets.SyntheticItemResponseTheory()\n vec_model = gym.targets.VectorModel(base_model)\n\n base_model.dtype\n # ==> {\n # 'mean_student_ability': tf.float32,\n # 'centered_student_ability': tf.float32,\n # 'question_difficulty': tf.float32,\n # }\n\n vec_model.dtype\n # ==> tf.float32\n\n base_model.event_shape\n # ==> {\n # 'mean_student_ability': [],\n # 'centered_student_ability': [400],\n # 'question_difficulty': [100],\n # }\n\n vec_model.event_shape\n # ==> [501]\n ```\n\n \"\"\"\n\n def __init__(self, model, flatten_sample_transformations=False):\n \"\"\"Constructs the adapter.\n\n Args:\n model: An Inference Gym model.\n flatten_sample_transformations: Python bool. Whether to flatten and\n concatenate the outputs of sample transformations.\n\n Raises:\n TypeError: If `model` has more than one unique Tensor dtype.\n TypeError: If `flatten_sample_transformations` is `True` and there is a\n sample transformation that has more than one unique Tensor dtype.\n \"\"\"\n self._model = model\n\n super(VectorModel, self).__init__(\n default_event_space_bijector=_make_vector_event_space_bijector(\n self._model),\n event_shape=_get_vector_event_shape(self._model),\n dtype=_get_unique_dtype(\n self._model.dtype,\n 'Model must have only one Tensor dtype, saw: {}'.format),\n name='vector_' + self._model.name,\n pretty_name=str(self._model),\n sample_transformations=_make_vector_sample_transformations(\n self._model, flatten_sample_transformations),\n )\n\n def _unnormalized_log_prob(self, value):\n return self._model.unnormalized_log_prob(\n _split_and_reshape_event(value, self._model))\n\n\ndef _flatten_and_concat(x, batch_shape, dtype):\n \"\"\"Flattens and concatenates a structured `x`.\"\"\"\n # For convenience.\n if x is None:\n return x\n\n def _reshape_part(part):\n part = tf.cast(part, dtype)\n new_shape = ps.concat(\n [batch_shape, [-1]],\n axis=-1,\n )\n return tf.reshape(part, ps.cast(new_shape, tf.int32))\n\n x = tf.nest.map_structure(_reshape_part, x)\n return tf.concat(tf.nest.flatten(x), axis=-1)\n\n\ndef _get_unique_dtype(dtype, error_message_fn):\n \"\"\"Gets unique singleton dtype from a structure.\"\"\"\n dtypes = set(tf.nest.flatten(tf.nest.map_structure(tf.as_dtype, dtype)))\n if len(dtypes) > 1:\n raise TypeError(error_message_fn(dtype))\n return dtypes.pop()\n\n\ndef _make_vector_event_space_bijector(model):\n \"\"\"Creates a vector bijector that constrains like the structured model.\"\"\"\n\n # TODO(siege): Make this work with multi-part default_event_bijector.\n def _make_reshaped_bijector(b, s):\n return tfb.Chain([\n tfb.Reshape(event_shape_in=s, event_shape_out=[ps.reduce_prod(s)]),\n b,\n tfb.Reshape(\n event_shape_in=[ps.reduce_prod(b.inverse_event_shape(s))],\n event_shape_out=b.inverse_event_shape(s)),\n ])\n\n reshaped_bijector = tf.nest.map_structure(_make_reshaped_bijector,\n model.default_event_space_bijector,\n model.event_shape)\n\n return tfb.Blockwise(\n bijectors=tf.nest.flatten(reshaped_bijector),\n block_sizes=tf.nest.flatten(\n tf.nest.map_structure(\n lambda b, s: ps.reduce_prod(b.inverse_event_shape(s)), # pylint: disable=g-long-lambda\n model.default_event_space_bijector,\n model.event_shape)))\n\n\ndef _get_vector_event_shape(model):\n \"\"\"Returns the size of the vector corresponding to the flattened event.\"\"\"\n event_sizes = tf.nest.map_structure(ps.reduce_prod, model.event_shape)\n return tf.TensorShape([sum(tf.nest.flatten(event_sizes))])\n\n\ndef _split_and_reshape_event(x, model):\n \"\"\"Splits and reshapes a flat event `x` to match the structure of `model`.\"\"\"\n splits = [\n ps.maximum(1, ps.reduce_prod(s))\n for s in tf.nest.flatten(model.event_shape)\n ]\n x = tf.nest.pack_sequence_as(model.event_shape, tf.split(x, splits, axis=-1))\n\n def _reshape_part(part, dtype, event_shape):\n part = tf.cast(part, dtype)\n new_shape = ps.concat([ps.shape(part)[:-1], event_shape], axis=-1)\n return tf.reshape(part, ps.cast(new_shape, tf.int32))\n\n x = tf.nest.map_structure(_reshape_part, x, model.dtype, model.event_shape)\n return x\n\n\ndef _make_vector_sample_transformations(model, flatten_sample_transformations):\n \"\"\"Makes `model`'s sample transformations compatible with vector events.\"\"\"\n sample_transformations = collections.OrderedDict()\n\n def flattened_transform(x, dtype, transform):\n res = transform(_split_and_reshape_event(x, model))\n if not flatten_sample_transformations:\n return res\n batch_shape = ps.shape(x)[:-1]\n return _flatten_and_concat(res, batch_shape, dtype)\n\n # We yank this out to avoid capturing the loop variable.\n def make_flattened_transform(transform_name, transform):\n if flatten_sample_transformations:\n dtype = _get_unique_dtype(\n transform.dtype,\n lambda d: # pylint: disable=g-long-lambda\n 'Sample transformation \\'{}\\' must have only one Tensor dtype, '\n 'saw: {}'.format(transform_name, d))\n transform = transform._replace(\n ground_truth_mean=_flatten_and_concat(\n transform.ground_truth_mean, (), dtype),\n ground_truth_standard_deviation=_flatten_and_concat(\n transform.ground_truth_standard_deviation, (), dtype),\n ground_truth_mean_standard_error=_flatten_and_concat(\n transform.ground_truth_mean_standard_error, (), dtype),\n ground_truth_standard_deviation_standard_error=_flatten_and_concat(\n transform.ground_truth_standard_deviation_standard_error, (),\n dtype),\n )\n else:\n dtype = None\n return transform._replace(\n fn=functools.partial(\n flattened_transform, dtype=dtype, transform=transform))\n\n for key, transform in model.sample_transformations.items():\n sample_transformations[key] = make_flattened_transform(key, transform)\n return sample_transformations\n", "# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n# Lint as: python3\n\"\"\"Tests for tensorflow_probability.spinoffs.oryx.util.summary.\"\"\"\n\nfrom absl.testing import absltest\n\nfrom jax import lax\nimport jax.numpy as jnp\nimport numpy as np\n\nfrom oryx.internal import test_util\nfrom oryx.util import summary\n\n\nclass SummaryTest(test_util.TestCase):\n\n def test_can_pull_out_summarized_values_in_strict_mode(self):\n def f(x):\n return summary.summary(x, name='x')\n _, summaries = summary.get_summaries(f)(1.)\n self.assertDictEqual(dict(x=1.), summaries)\n\n def test_can_pull_out_non_dependent_values(self):\n def f(x):\n summary.summary(x ** 2, name='y')\n return x\n _, summaries = summary.get_summaries(f)(2.)\n self.assertDictEqual(dict(y=4.), summaries)\n\n def test_duplicate_names_error_in_strict_mode(self):\n def f(x):\n summary.summary(x, name='x')\n summary.summary(x, name='x')\n return x\n with self.assertRaisesRegex(ValueError, 'has already been reaped: x'):\n summary.get_summaries(f)(2.)\n\n def test_can_append_to_growing_list_with_summary(self):\n def f(x):\n summary.summary(x + 1., name='x', mode='append')\n summary.summary(x + 2., name='x', mode='append')\n return x\n _, summaries = summary.get_summaries(f)(2.)\n self.assertSetEqual(set(summaries.keys()), {'x'})\n np.testing.assert_allclose(summaries['x'], np.array([3., 4.]))\n\n def test_can_pull_summaries_out_of_scan_in_append_mode(self):\n def f(x):\n def body(x, _):\n summary.summary(x, name='x', mode='append')\n return x + 1, ()\n return lax.scan(body, x, jnp.arange(10.))[0]\n value, summaries = summary.get_summaries(f)(0.)\n self.assertEqual(value, 10.)\n np.testing.assert_allclose(summaries['x'], np.arange(10.))\n\n\nif __name__ == '__main__':\n absltest.main()\n", "# Lint as: python3\n# Copyright 2020 The TensorFlow Probability 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\"\"\"NonIdentifiableQuarticMeasurementModel model.\"\"\"\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\n\nfrom inference_gym.targets import bayesian_model\nfrom inference_gym.targets import model\n\ntfb = tfp.bijectors\ntfd = tfp.distributions\n\n__all__ = [\n 'NonIdentifiableQuarticMeasurementModel',\n]\n\n\nclass NonIdentifiableQuarticMeasurementModel(bayesian_model.BayesianModel):\n \"\"\"A non-identifiable model with a quartic measurement model.\n\n This distribution is defined in [1] as the posterior induced by the following\n model:\n\n ```none\n for i in range(ndims):\n theta[i] ~ Normal(loc=0, scale=1)\n F(theta) = theta[1]**2 + 3 * theta[0]**2 * (theta[0]**2 - 1)\n y ~ Normal(loc=F(theta), scale=noise_scale)\n ```\n\n with an observed `y = 1`. Note that if `ndims` is > 2, the additional\n dimensions are distributed as a standard normal.\n\n This distribution is notable for having density on a narrow manifold which\n requires small step sizes when using HMC. It also happens to be multi-modal (4\n modes), but the modes are not well separated and should not pose challenge to\n most inference methods.\n\n #### References\n\n 1. Au, K. X., Graham, M. M., & Thiery, A. H. (2020). Manifold lifting: scaling\n MCMC to the vanishing noise regime. (2), 1-18. Retrieved from\n http://arxiv.org/abs/2003.03950\n \"\"\"\n\n def __init__(\n self,\n ndims=2,\n noise_scale=0.1,\n name='non_identifiable_quartic_measurement_model',\n pretty_name='Non-Identifiable Quartic Measurement Model',\n ):\n \"\"\"Construct the NonIdentifiableQuarticMeasurementModel model.\n\n Args:\n ndims: Python integer. Dimensionality of the distribution. Must be at\n least 2.\n noise_scale: Floating point Tensor. Scale of the observation noise.\n name: Python `str` name prefixed to Ops created by this class.\n pretty_name: A Python `str`. The pretty name of this model.\n\n Raises:\n ValueError: If ndims < 2.\n \"\"\"\n if ndims < 2:\n raise ValueError('ndims must be at least 2, saw: {}'.format(ndims))\n\n with tf.name_scope(name):\n\n sample_transformations = {\n 'identity':\n model.Model.SampleTransformation(\n fn=lambda params: params,\n pretty_name='Identity',\n ground_truth_mean=np.zeros(ndims), # By symmetry.\n )\n }\n\n self._prior_dist = tfd.Sample(tfd.Normal(0., 1.), ndims)\n self._noise_scale = tf.convert_to_tensor(\n noise_scale, dtype_hint=tf.float32)\n\n super(NonIdentifiableQuarticMeasurementModel, self).__init__(\n default_event_space_bijector=tfb.Identity(),\n event_shape=self._prior_dist.event_shape,\n dtype=self._prior_dist.dtype,\n name=name,\n pretty_name=pretty_name,\n sample_transformations=sample_transformations,\n )\n\n def _prior_distribution(self):\n return self._prior_dist\n\n def _log_likelihood(self, value):\n theta_0_sq = value[..., 0]**2\n theta_1_sq = value[..., 1]**2\n y_hat = theta_1_sq + 3 * theta_0_sq * (theta_0_sq - 1.)\n y = 1.\n observation_dist = tfd.Normal(y_hat, self._noise_scale)\n return observation_dist.log_prob(y)\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"KumaraswamyCDF bijector.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.bijectors import bijector\nfrom tensorflow_probability.python.bijectors import softplus as softplus_bijector\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import auto_composite_tensor\nfrom tensorflow_probability.python.internal import distribution_util\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import parameter_properties\nfrom tensorflow_probability.python.internal import tensor_util\n\n\n__all__ = [\n 'KumaraswamyCDF',\n]\n\n\n@auto_composite_tensor.auto_composite_tensor(\n omit_kwargs=('name',), module_name='tfp.bijectors')\nclass KumaraswamyCDF(bijector.AutoCompositeTensorBijector):\n \"\"\"Compute `Y = g(X) = (1 - X**a)**b, X in [0, 1]`.\n\n This bijector maps inputs from `[0, 1]` to `[0, 1]`. The inverse of the\n bijector applied to a uniform random variable `X ~ U(0, 1)` gives back a\n random variable with the [Kumaraswamy distribution](\n https://en.wikipedia.org/wiki/Kumaraswamy_distribution):\n\n ```none\n Y ~ Kumaraswamy(a, b)\n pdf(y; a, b, 0 <= y <= 1) = a * b * y ** (a - 1) * (1 - y**a) ** (b - 1)\n ```\n \"\"\"\n\n def __init__(self,\n concentration1=1.,\n concentration0=1.,\n validate_args=False,\n name='kumaraswamy_cdf'):\n \"\"\"Instantiates the `KumaraswamyCDF` bijector.\n\n Args:\n concentration1: Python `float` scalar indicating the transform power,\n i.e., `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)` where `a` is\n `concentration1`.\n concentration0: Python `float` scalar indicating the transform power,\n i.e., `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)` where `b` is\n `concentration0`.\n validate_args: Python `bool` indicating whether arguments should be\n checked for correctness.\n name: Python `str` name given to ops managed by this object.\n \"\"\"\n parameters = dict(locals())\n with tf.name_scope(name) as name:\n dtype = dtype_util.common_dtype([concentration0, concentration1],\n dtype_hint=tf.float32)\n self._concentration0 = tensor_util.convert_nonref_to_tensor(\n concentration0, dtype=dtype, name='concentration0')\n self._concentration1 = tensor_util.convert_nonref_to_tensor(\n concentration1, dtype=dtype, name='concentration1')\n super(KumaraswamyCDF, self).__init__(\n forward_min_event_ndims=0,\n validate_args=validate_args,\n parameters=parameters,\n name=name)\n\n @classmethod\n def _parameter_properties(cls, dtype):\n return dict(\n concentration0=parameter_properties.ParameterProperties(\n default_constraining_bijector_fn=(\n lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype)))),\n concentration1=parameter_properties.ParameterProperties(\n default_constraining_bijector_fn=(\n lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype)))))\n\n @property\n def concentration1(self):\n \"\"\"The `a` in: `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)`.\"\"\"\n return self._concentration1\n\n @property\n def concentration0(self):\n \"\"\"The `b` in: `Y = g(X) = (1 - (1 - X)**(1 / b))**(1 / a)`.\"\"\"\n return self._concentration0\n\n @classmethod\n def _is_increasing(cls):\n return True\n\n def _inverse(self, y):\n y = self._maybe_assert_valid(y)\n return tf.exp(\n tf.math.log1p(-tf.exp(tf.math.log1p(-y) / self.concentration0)) /\n self.concentration1)\n\n def _forward(self, x):\n x = self._maybe_assert_valid(x)\n return -tf.math.expm1(self.concentration0 * tf.math.log1p(\n -(x ** self.concentration1)))\n\n def _forward_log_det_jacobian(self, x):\n x = self._maybe_assert_valid(x)\n concentration1 = tf.convert_to_tensor(self.concentration1)\n concentration0 = tf.convert_to_tensor(self.concentration0)\n return (tf.math.log(concentration1) +\n tf.math.log(concentration0) +\n tf.math.xlogy(concentration1 - 1, x) +\n tf.math.xlog1py(concentration0 - 1, -x**concentration1))\n\n def _maybe_assert_valid(self, x):\n if not self.validate_args:\n return x\n return distribution_util.with_dependencies([\n assert_util.assert_non_negative(\n x, message='Sample must be non-negative.'),\n assert_util.assert_less_equal(\n x,\n tf.ones([], self.concentration0.dtype),\n message='Sample must be less than or equal to `1`.'),\n ], x)\n\n def _parameter_control_dependencies(self, is_init):\n if not self.validate_args:\n return []\n assertions = []\n if is_init != tensor_util.is_ref(self.concentration0):\n assertions.append(assert_util.assert_positive(\n self.concentration0,\n message='Argument `concentration0` must be positive.'))\n if is_init != tensor_util.is_ref(self.concentration1):\n assertions.append(assert_util.assert_positive(\n self.concentration1,\n message='Argument `concentration1` must be positive.'))\n return assertions\n", "# Lint as: python2, python3\n# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Functions for framing `conv` as `matmul`.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.experimental.nn.util import utils\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import prefer_static as ps\n\n__all__ = [\n 'im2row',\n 'im2row_index',\n 'make_convolution_fn',\n 'make_convolution_transpose_fn_with_dilation',\n 'make_convolution_transpose_fn_with_subkernels',\n 'make_convolution_transpose_fn_with_subkernels_matrix',\n]\n\n\ndef im2row(x,\n block_shape,\n slice_step=(1, 1),\n padding='VALID',\n name=None):\n \"\"\"Rearrange image blocks into rows.\n\n This function can be used to implement 2D convolution as a `matmul`, e.g.,\n\n `tf.nn.conv2d(x, k) = tf.matmul(\n tf.experimental.nn.util.im2row(x), tf.reshape(k, shape=[-1, out_size]))`.\n\n Args:\n x: Rank 3 (or more) Tensor representing 2D images.\n block_shape: Length-2 vector representing the block or \"filter\" shape.\n slice_step: Length-2 vector specifying the convolution stride length.\n Default value: `(1, 1)`.\n padding: One of `'VALID'` or `'SAME'` (case insensitive).\n Default value: `'VALID'`.\n name: Python `str` used to describe ops created by this function.\n Default value: `None` (i.e., `'im2col'`).\n\n Returns:\n im2row_x: batch of matrices representing subblock copies of `x`.\n Same batch shape as `x` but with rightmost shape:\n `batch_shape + [oh * ow, block_shape[0] * block_shape[1] * channels]`,\n where `oh = (h - block_shape[0] + 1) // slice_step[0]` and\n `ow = (w - block_shape[1] + 1) // slice_step[1]` when `padding = 'VALID'`\n and `oh = h` and `ow = w` when `padding = 'SAME'`.\n shape: shape `Tensor` equivalent to:\n `batch_shape + [oh, ow, block_shape[0] * block_shape[1] * channels]` where\n `oh, ow` are defined as above.\n \"\"\"\n with tf.name_scope(name or 'im2row'):\n padding = _validate_padding(padding)\n if padding == 'VALID':\n pass # Do nothing.\n elif padding == 'SAME':\n raise NotImplementedError(\n 'Argument padding=\"SAME\" not implemented.')\n # TODO(jvdillon): See if the following works:\n # fh, fw = block_shape\n # o = 1 if data_format == 'NHWC' else 0\n # n = ps.maximum(0, ps.rank(x) - 3)\n # paddings = ps.pad(\n # [[0, fh - 1], [0, fw - 1]],\n # paddings=[[n + 1 - o, o], [0, 0]],\n # constant_values=0)\n # x = tf.pad(x, paddings=paddings, constant_values=0)\n # padding = 'VALID'\n else:\n assert False # Can't be here.\n x_shape = ps.shape(x)\n idx, s = im2row_index(\n x_shape, block_shape=block_shape, slice_step=slice_step)\n flat_shape = ps.pad(\n x_shape[:-3], paddings=[[0, 1]], constant_values=-1)\n x = tf.gather(tf.reshape(x, flat_shape), idx, axis=-1) # == np.take\n return tf.reshape(x, s)\n\n\ndef im2row_index(input_shape,\n block_shape,\n rank=2,\n slice_step=(1, 1),\n dilations=(1, 1),\n dtype=tf.int32,\n transpose=False,\n validate_args=False,\n name=None):\n \"\"\"Computes indexes into a flattened image for building `im2row`.\"\"\"\n with tf.name_scope(name or 'im2row_index'):\n if tf.get_static_value(rank) != 2:\n raise NotImplementedError('Argument `rank` currently only supports `2`; '\n 'saw \"{}\".'.format(rank))\n fh, fw = prepare_tuple_argument(\n block_shape, n=rank, arg_name='block_shape',\n validate_args=validate_args)\n sh, sw = prepare_tuple_argument(\n slice_step, n=rank, arg_name='slice_step', validate_args=validate_args)\n dh, dw = prepare_tuple_argument(\n dilations, n=rank, arg_name='dilations', validate_args=validate_args)\n\n # 1) Process input arguments.\n batch_shape, h, w, c = ps.split(\n ps.reshape(ps.cast(input_shape, dtype=dtype), shape=[-1]),\n num_or_size_splits=[-1, 1, 1, 1])\n h, w, c = h[0], w[0], c[0]\n\n tot_fh = dh * (fh - 1) + 1\n tot_fw = dw * (fw - 1) + 1\n\n # 2) Assemble all block start positions as indexes into the flattened image.\n # start_idx.shape = [fh, fw, c]\n if transpose:\n last_element = lambda size, step: size - (size - 1) % step - 1\n w_step = c * dw\n h_step = c * w * dh\n last_w = last_element(c * tot_fw, w_step)\n last_h = last_element(c * w * tot_fh, h_step)\n start_idx = cartesian_add([\n ps.range(last_h, -1, delta=-h_step, dtype=dtype),\n ps.range(last_w, -1, delta=-w_step, dtype=dtype),\n ps.range(c, delta=1, dtype=dtype),\n ])\n else:\n start_idx = cartesian_add([\n ps.range(c * w * tot_fh, delta=c * w * dh, dtype=dtype),\n ps.range(c * tot_fw, delta=c * dw, dtype=dtype),\n ps.range(c, delta=1, dtype=dtype),\n ])\n\n # 3) Assemble all block offsets (into flattened image).\n eh = h - tot_fh + 1\n ew = w - tot_fw + 1\n\n offset_idx = cartesian_add([\n ps.range(w * eh, delta=w * sh, dtype=dtype),\n ps.range(ew, delta=sw, dtype=dtype),\n ])\n\n offset_idx = offset_idx * c\n oh = (eh - 1) // sh + 1 # out height\n ow = (ew - 1) // sw + 1 # out width\n\n # 4) Combine block start/offset pairs.\n # shape = [(eh // sh) * (ew // sw), fh * fw * c]\n idx = cartesian_add([offset_idx, start_idx])\n new_shape = ps.concat(\n [batch_shape, ps.convert_to_shape_tensor([oh, ow, fh * fw * c])],\n axis=0)\n return idx, new_shape\n\n\ndef cartesian_add(xs):\n \"\"\"Adds a list of vectors by cumulatively expanding a dimension.\"\"\"\n return sum(ps.reshape(x, shape=[-1] + [1] * (len(xs) - 1 - i))\n for i, x in enumerate(xs))\n\n\ndef _validate_padding(padding):\n \"\"\"Verify correctness of `padding` argument.\"\"\"\n padding_ = str(padding).upper()\n if padding_ in {'SAME', 'VALID'}:\n return padding_\n raise ValueError(\n 'Argument padding=\"{}\" not recognized; must be one of '\n '{{\"VALID\", \"SAME\"}} (case insensitive).'.format(padding))\n\n\n# TODO(emilyaf): Finish docstrings.\ndef make_convolution_fn(\n filter_shape, rank, strides, padding, dilations=None, dtype=tf.int32,\n validate_args=False, name=None):\n \"\"\"Like `tf.nn.conv2d` except applies batch of kernels to batch of `x`.\"\"\"\n with tf.name_scope(name or 'conv2d'):\n if tf.get_static_value(rank) != 2:\n raise NotImplementedError('Argument `rank` currently only supports `2`; '\n 'saw \"{}\".'.format(rank))\n [\n filter_shape,\n rank,\n strides,\n padding,\n dilations,\n ] = prepare_conv_args(\n filter_shape, rank=rank, strides=strides, padding=padding,\n dilations=dilations, validate_args=validate_args)\n\n def op(x, kernel):\n input_dtype = dtype_util.common_dtype([x, kernel], dtype_hint=tf.float32)\n x = tf.convert_to_tensor(x, dtype=input_dtype, name='x')\n kernel = tf.convert_to_tensor(kernel, dtype=input_dtype, name='kernel')\n\n batch_shape, event_shape = ps.split(\n ps.shape(x), num_or_size_splits=[-1, 3])\n xh, xw, c_in = ps.unstack(event_shape, num=3)\n fh, fw = filter_shape\n\n assertions = _maybe_validate_input_shapes(\n ps.shape(kernel), channels_in=c_in, filter_height=fh,\n filter_width=fw, validate_args=validate_args)\n\n with tf.control_dependencies(assertions):\n if tf.get_static_value(ps.rank(kernel)) == 2:\n flat_x = tf.reshape(x, shape=ps.concat([[-1], event_shape], axis=0))\n flat_y = tf.nn.conv2d(\n x,\n filters=tf.reshape(kernel, shape=[fh, fw, c_in, -1]),\n strides=strides,\n padding=padding,\n data_format='NHWC',\n dilations=dilations)\n output_shape = ps.shape(flat_y)[-3:]\n return tf.reshape(\n flat_y, shape=ps.concat([batch_shape, output_shape], axis=0))\n\n pad_values = [\n _get_conv_padding(\n xdim, filter_dim=k, stride=s, dilation=d, padding=padding)\n for (xdim, k, s, d) in zip((xh, xw), filter_shape, strides, dilations)\n ]\n\n idx, shape = im2row_index(\n (xh + sum(pad_values[0]), xw + sum(pad_values[1]), c_in),\n block_shape=filter_shape, slice_step=strides, dilations=dilations,\n dtype=dtype)\n\n if padding == 'SAME':\n n = ps.maximum(0, ps.rank(x) - 3)\n paddings = ps.pad(\n pad_values, paddings=[[n, 1], [0, 0]], constant_values=0)\n x = tf.pad(x, paddings=paddings, constant_values=0)\n\n flat_shape = ps.pad(\n batch_shape, paddings=[[0, 1]], constant_values=-1)\n flat_x = tf.gather(tf.reshape(x, shape=flat_shape), indices=idx, axis=-1)\n im_x = tf.reshape(flat_x, shape=ps.concat([batch_shape, shape], axis=0))\n return tf.matmul(im_x, kernel[..., tf.newaxis, :, :])\n return op\n\n\ndef _get_conv_padding(xdim, filter_dim, stride, dilation, padding):\n \"\"\"Returns the number of zeros to pad at the start and end of an axis.\"\"\"\n if padding == 'VALID':\n return (0, 0)\n elif padding == 'SAME':\n tot_k = dilation * (filter_dim - 1) + 1\n tot_pad = tf.maximum(tot_k - ((xdim - 1) % stride + 1), 0)\n pad_start = tot_pad // 2\n return pad_start, tot_pad - pad_start\n\n\ndef make_convolution_transpose_fn_with_dilation(\n filter_shape, strides, padding, rank=2, dilations=None, dtype=tf.int32,\n validate_args=False, name=None):\n \"\"\"Like `tf.nn.conv2d` except applies batch of kernels to batch of `x`.\n\n This version tends to be fastest on GPU. It implements the transposed\n convolution as a regular convolution of an image that is dilated by\n interleaving rows and columns of zeros equal to the number of strides.\n\n Args:\n filter_shape: ...\n strides: ...\n padding: ...\n rank: ...\n dilations: ...\n dtype: ...\n validate_args: ...\n name: ...\n Returns:\n convolution_transpose_fn: A callable that takes an input `Tensor` and kernel\n and applies the transpose convolution operation.\n \"\"\"\n with tf.name_scope(name or 'make_convolution_transpose_fn_with_dilation'):\n\n if tf.get_static_value(rank) != 2:\n raise NotImplementedError('Argument `rank` currently only supports `2`; '\n 'saw \"{}\".'.format(rank))\n [\n filter_shape,\n rank,\n strides,\n padding,\n dilations,\n ] = prepare_conv_args(\n filter_shape, rank=rank, strides=strides, padding=padding,\n dilations=dilations, is_transpose=True, validate_args=validate_args)\n\n sh, sw = strides\n fh, fw = filter_shape\n\n pad_values = [\n _get_transpose_conv_dilated_padding(\n k, stride=s, dilation=d, padding=padding)\n for (k, s, d) in zip(filter_shape, strides, dilations)]\n\n def op(x, kernel):\n input_dtype = dtype_util.common_dtype([x, kernel], dtype_hint=tf.float32)\n x = tf.convert_to_tensor(x, dtype=input_dtype, name='x')\n kernel = tf.convert_to_tensor(kernel, dtype=input_dtype, name='kernel')\n\n batch_shape, event_shape = ps.split(\n ps.shape(x), num_or_size_splits=[-1, 3])\n xh, xw, c_in = ps.unstack(event_shape, num=3)\n kernel_shape = ps.shape(kernel)\n assertions = _maybe_validate_input_shapes(\n kernel_shape, channels_in=c_in, filter_height=fh, filter_width=fw,\n validate_args=validate_args)\n\n with tf.control_dependencies(assertions):\n # If the kernel does not have batch shape, fall back to\n # `conv2d_transpose` (unless dilations > 1, which is not implemented in\n # `conv2d_transpose`).\n if (tf.get_static_value(ps.rank(kernel)) == 2\n and all(d == 1 for d in dilations)):\n return _call_conv2d_transpose(\n x, kernel, filter_shape, strides, padding, dilations,\n kernel_shape[-1], batch_shape, event_shape)\n\n idx, shape = im2row_index(\n (xh * sh + sum(pad_values[0]), xw * sw + sum(pad_values[1]), c_in),\n block_shape=filter_shape, slice_step=(1, 1), dilations=dilations,\n dtype=dtype, transpose=True)\n\n n = ps.maximum(0, ps.rank(x) - 3)\n paddings = ps.pad(\n pad_values, paddings=[[n, 1], [0, 0]], constant_values=0)\n\n # Interleave the rows and columns of the input with rows and columns of\n # zeros equal to the number of strides.\n x_half_dilated = tf.concat(\n [tf.zeros(ps.concat([batch_shape, (xh * xw, sw - 1, c_in)], axis=0),\n dtype=input_dtype),\n tf.reshape(\n x, shape=ps.concat([batch_shape, (xh * xw, 1, c_in)], axis=0))\n ], axis=-2)\n y = tf.reshape(\n x_half_dilated,\n shape=ps.concat([batch_shape, (xh, 1, xw * sw, c_in)], axis=0))\n\n x = tf.reshape(\n tf.concat(\n [tf.zeros(\n ps.concat(\n [batch_shape, (xh, sh - 1, xw * sw, c_in)], axis=0),\n dtype=input_dtype), y], axis=-3),\n shape=ps.concat([batch_shape, (xh * sh, xw * sw, c_in)], axis=0))\n\n truncations = -ps.minimum(ps.cast(paddings, dtype=tf.int32), 0)\n truncate_start, truncate_end = ps.unstack(truncations, axis=1)\n x_truncate = tf.slice(\n x,\n begin=truncate_start,\n size=ps.shape(x) - (truncate_start + truncate_end))\n\n x_pad = tf.pad(\n x_truncate, paddings=ps.maximum(paddings, 0), constant_values=0)\n\n flat_shape = ps.pad(batch_shape, paddings=[[0, 1]], constant_values=-1)\n flat_x = tf.gather(\n tf.reshape(x_pad, shape=flat_shape), indices=idx, axis=-1)\n im_x = tf.reshape(flat_x, shape=ps.concat([batch_shape, shape], axis=0))\n return tf.matmul(im_x, kernel[..., tf.newaxis, :, :])\n return op\n\n\ndef make_convolution_transpose_fn_with_subkernels_matrix(\n filter_shape, strides, padding, rank=2, dilations=None, dtype=tf.int32,\n validate_args=False, name=None):\n \"\"\"Like `tf.nn.conv2d` except applies batch of kernels to batch of `x`.\"\"\"\n with tf.name_scope(name or 'make_convolution_transpose_fn_with_dilation'):\n\n if tf.get_static_value(rank) != 2:\n raise NotImplementedError('Argument `rank` currently only supports `2`; '\n 'saw \"{}\".'.format(rank))\n\n strides = tf.get_static_value(strides)\n if not isinstance(strides, int):\n raise ValueError('Argument `strides` must be a statically known integer.'\n 'Saw: {}'.format(strides))\n\n [\n filter_shape,\n rank,\n _,\n padding,\n dilations,\n ] = prepare_conv_args(\n filter_shape, rank=rank, strides=strides, padding=padding,\n dilations=dilations, is_transpose=True, validate_args=validate_args)\n\n fh, fw = filter_shape\n dh, dw = dilations\n\n # Determine maximum filter height and filter width of sub-kernels.\n sub_fh = (fh - 1) // strides + 1\n sub_fw = (fw - 1) // strides + 1\n\n def loop_body(i_, event_ind):\n i = i_ // strides\n j = i_ % strides\n\n i_ind = ps.range(\n i * fw, ps.maximum(i, fh) * fw, delta=strides * fw, dtype=dtype)\n j_ind = ps.range(j, ps.maximum(j, fw), delta=strides, dtype=dtype)\n\n nc = cartesian_add([i_ind, j_ind])\n ind = ps.reverse(ps.reshape(nc, shape=[-1]), axis=[0])\n\n k = ps.reshape(\n cartesian_add(\n [ps.range(ps.shape(nc)[0] * sub_fw, delta=sub_fw, dtype=dtype),\n ps.range(ps.shape(nc)[1], dtype=dtype)]),\n shape=[-1])\n last_j = strides - (fw - j - 1) % strides - 1\n last_i = strides - (fh - i - 1) % strides - 1\n kernel_ind = ps.stack(\n [k, ps.ones_like(k) * last_i * strides + last_j], axis=1)\n event_ind = ps.tensor_scatter_nd_update(\n event_ind, ind[..., tf.newaxis], kernel_ind)\n\n return i_ + 1, event_ind\n\n event_ind = ps.zeros((fh * fw, 2), dtype=dtype)\n _, event_ind = tf.while_loop(\n lambda i, _: i < strides ** 2,\n loop_body,\n [tf.zeros([], dtype=dtype), event_ind])\n\n tot_pad_top, tot_pad_bottom = _get_transpose_conv_dilated_padding(\n fh, stride=strides, dilation=dh, padding=padding)\n tot_pad_left, tot_pad_right = _get_transpose_conv_dilated_padding(\n fw, stride=strides, dilation=dw, padding=padding)\n\n pad_bottom = (tot_pad_bottom - 1) // strides + 1\n pad_top = (tot_pad_top - 1) // strides + 1\n pad_right = (tot_pad_right - 1) // strides + 1\n pad_left = (tot_pad_left - 1) // strides + 1\n padding_vals = ((pad_top, pad_bottom), (pad_left, pad_right))\n\n truncate_top = pad_top * strides - tot_pad_top\n truncate_left = pad_left * strides - tot_pad_left\n\n def op(x, kernel):\n input_dtype = dtype_util.common_dtype([x, kernel], dtype_hint=tf.float32)\n x = tf.convert_to_tensor(x, dtype=input_dtype, name='x')\n kernel = tf.convert_to_tensor(kernel, dtype=input_dtype, name='kernel')\n\n batch_shape, event_shape = ps.split(\n ps.shape(x), num_or_size_splits=[-1, 3])\n xh, xw, c_in = ps.unstack(event_shape, num=3)\n\n kernel_shape = ps.shape(kernel)\n c_out = kernel_shape[-1]\n kernel_batch = kernel_shape[:-2]\n assertions = _maybe_validate_input_shapes(\n kernel_shape, channels_in=c_in, filter_height=fh, filter_width=fw,\n validate_args=validate_args)\n\n with tf.control_dependencies(assertions):\n\n # If the kernel does not have batch shape, fall back to\n # `conv2d_transpose` (unless dilations > 1, which is not implemented in\n # `conv2d_transpose`).\n if (tf.get_static_value(ps.rank(kernel)) == 2\n and all(d == 1 for d in dilations)):\n return _call_conv2d_transpose(\n x, kernel=kernel, filter_shape=filter_shape,\n strides=(strides,) * rank, padding=padding, dilations=dilations,\n c_out=c_out, batch_shape=batch_shape, event_shape=event_shape)\n\n n = ps.maximum(0, ps.rank(x) - 3)\n paddings = ps.pad(\n padding_vals,\n paddings=[[n, 1], [0, 0]],\n constant_values=0)\n\n x_pad = tf.pad(x, paddings=paddings, constant_values=0)\n x_pad_shape = ps.shape(x_pad)[:-3]\n flat_shape = ps.pad(x_pad_shape, paddings=[[0, 1]], constant_values=-1)\n flat_x = tf.reshape(x_pad, shape=flat_shape)\n\n idx, s = im2row_index(\n (xh + tf.reduce_sum(padding_vals[0]),\n xw + tf.reduce_sum(padding_vals[1]), c_in),\n block_shape=(sub_fh, sub_fw), slice_step=(1, 1), dilations=dilations\n )\n\n x_ = tf.gather(flat_x, indices=idx, axis=-1)\n im_x = tf.reshape(x_, shape=ps.concat([x_pad_shape, s], axis=0))\n\n # Add channels to subkernel indices\n idx_event = event_ind * [[c_in, 1]]\n idx_event_channels = (\n idx_event[tf.newaxis]\n + tf.stack([ps.range(c_in), tf.zeros((c_in,), dtype=dtype)],\n axis=-1)[:, tf.newaxis, :])\n idx_event = tf.squeeze(\n tf.batch_to_space(\n idx_event_channels, block_shape=[c_in], crops=[[0, 0]]), axis=0)\n idx_event_broadcast = tf.broadcast_to(\n idx_event,\n shape=ps.concat([kernel_batch, ps.shape(idx_event)], axis=0))\n\n # Add cartesian product of batch indices, since scatter_nd can only be\n # applied to leading dimensions.\n idx_batch = tf.stack(\n tf.meshgrid(\n *[ps.range(b_, delta=1, dtype=dtype)\n for b_ in tf.unstack(kernel_batch)], indexing='ij'),\n axis=ps.size(kernel_batch))\n\n idx_batch = tf.cast(idx_batch, dtype=dtype) # empty tensor is float\n\n idx_batch_broadcast = idx_batch[..., tf.newaxis, :] + tf.zeros(\n (ps.shape(idx_event)[0], 1), dtype=dtype)\n idx_kernel = tf.concat(\n [idx_batch_broadcast, idx_event_broadcast], axis=-1)\n\n kernel_mat = tf.scatter_nd(\n idx_kernel,\n updates=kernel,\n shape=ps.cast(\n ps.concat([kernel_batch,\n [sub_fh * sub_fw * c_in, strides ** 2, c_out]],\n axis=0),\n dtype=dtype))\n\n kernel_mat = tf.reshape(\n kernel_mat,\n shape=ps.concat(\n [ps.shape(kernel_mat)[:-2], [strides ** 2 * c_out]], axis=0))\n\n kernel_mat = kernel_mat[..., tf.newaxis, :, :]\n out = tf.matmul(im_x, kernel_mat)\n broadcast_batch_shape = ps.broadcast_shape(batch_shape, kernel_batch)\n\n if strides > 1:\n tot_size = tf.reduce_prod(broadcast_batch_shape)\n flat_out = tf.reshape(\n out,\n shape=ps.concat([[tot_size], ps.shape(out)[-3:]], axis=0))\n out = tf.nn.depth_to_space(flat_out, block_size=strides)\n\n out_height = _deconv_output_length(\n xh, filter_size=fh, padding=padding, output_padding=None,\n stride=strides, dilation=dh)\n out_width = _deconv_output_length(\n xw, filter_size=fw, padding=padding, output_padding=None,\n stride=strides, dilation=dw)\n\n out = out[..., truncate_top:truncate_top + out_height,\n truncate_left:truncate_left + out_width, :]\n out = tf.reshape(\n out, shape=ps.concat(\n [broadcast_batch_shape, [out_height, out_width, c_out]],\n axis=0))\n return out\n return op\n\n\ndef make_convolution_transpose_fn_with_subkernels(\n filter_shape, strides, padding, rank=2, dilations=None, dtype=tf.int32,\n validate_args=False, name=None):\n \"\"\"Like `tf.nn.conv2d` except applies batch of kernels to batch of `x`.\"\"\"\n with tf.name_scope(name or 'make_convolution_transpose_fn_with_dilation'):\n\n # Enable v2 control flow to avoid None gradients through TensorArray.\n tf.compat.v1.enable_control_flow_v2()\n\n if tf.get_static_value(rank) != 2:\n raise NotImplementedError('Argument `rank` currently only supports `2`; '\n 'saw \"{}\".'.format(rank))\n [\n filter_shape,\n rank,\n strides,\n padding,\n dilations,\n ] = prepare_conv_args(\n filter_shape, rank=rank, strides=strides, padding=padding,\n dilations=dilations, is_transpose=True, validate_args=validate_args)\n\n sh, sw = strides\n fh, fw = filter_shape\n dh, dw = dilations\n\n # Determine maximum filter height and filter width of sub-kernels.\n sub_fh = (fh - 1) // sh + 1\n sub_fw = (fw - 1) // sw + 1\n\n def loop_body(i_, kernels_ind):\n i = i_ // sw\n j = i_ % sw\n\n i_ind = ps.range(\n i * fw, ps.maximum(i, fh) * fw, delta=sh * fw, dtype=dtype)\n j_ind = ps.range(j, ps.maximum(j, fw), delta=sw, dtype=dtype)\n\n last_j = sw - (fw - j - 1) % sw - 1\n last_i = sh - (fh - i - 1) % sh - 1\n pos = last_i * sw + last_j\n\n nc = cartesian_add([i_ind, j_ind])\n kernels_ind = kernels_ind.write(\n pos, ps.reverse(ps.reverse(nc, [0]), [1]))\n return i_ + 1, kernels_ind\n\n kernels_ind = tf.TensorArray(dtype=dtype, infer_shape=False, size=sh * sw)\n\n _, kernels_ind = tf.while_loop(\n lambda i, _: i < sh * sw,\n loop_body,\n [0, kernels_ind])\n\n tot_pad_top, tot_pad_bottom = _get_transpose_conv_dilated_padding(\n fh, stride=sh, dilation=dh, padding=padding)\n tot_pad_left, tot_pad_right = _get_transpose_conv_dilated_padding(\n fw, stride=sw, dilation=dw, padding=padding)\n\n pad_bottom = (tot_pad_bottom - 1) // sh + 1\n pad_top = (tot_pad_top - 1) // sh + 1\n pad_right = (tot_pad_right - 1) // sw + 1\n pad_left = (tot_pad_left - 1) // sw + 1\n padding_vals = ((pad_top, pad_bottom), (pad_left, pad_right))\n\n truncate_top = pad_top * sh - tot_pad_top\n truncate_left = pad_left * sw - tot_pad_left\n\n def op(x, kernel):\n input_dtype = dtype_util.common_dtype([x, kernel], dtype_hint=tf.float32)\n x = tf.convert_to_tensor(x, dtype=input_dtype, name='x')\n kernel = tf.convert_to_tensor(kernel, dtype=input_dtype, name='kernel')\n\n batch_shape, event_shape = ps.split(\n ps.shape(x), num_or_size_splits=[-1, 3])\n xh, xw, c_in = ps.unstack(event_shape, num=3)\n\n kernel_shape = ps.shape(kernel)\n c_out = kernel_shape[-1]\n kernel_batch = kernel_shape[:-2]\n assertions = _maybe_validate_input_shapes(\n kernel_shape, channels_in=c_in, filter_height=fh, filter_width=fw,\n validate_args=validate_args)\n\n with tf.control_dependencies(assertions):\n # If the kernel does not have batch shape, fall back to\n # `conv2d_transpose` (unless dilations > 1, which is not implemented in\n # `conv2d_transpose`).\n if (tf.get_static_value(ps.rank(kernel)) == 2\n and all(d == 1 for d in dilations)):\n return _call_conv2d_transpose(\n x, kernel, filter_shape, strides, padding, dilations, c_out,\n batch_shape, event_shape)\n\n n = ps.maximum(0, ps.rank(x) - 3)\n paddings = ps.pad(\n padding_vals,\n paddings=[[n, 1], [0, 0]],\n constant_values=0)\n x_pad = tf.pad(x, paddings=paddings, constant_values=0)\n\n ex_h = xh + tf.reduce_sum(padding_vals[0]) - sub_fh + 1\n ex_w = xw + tf.reduce_sum(padding_vals[1]) - sub_fw + 1\n\n def loop_body(i, outputs):\n subkernel_ind = kernels_ind.read(i)\n fh_, fw_ = ps.unstack(ps.shape(subkernel_ind), num=2)\n eh = ex_h + fh_ - 1\n ew = ex_w + fw_ - 1\n\n subkernel_ind = ps.reshape(\n ps.reshape(subkernel_ind * c_in, shape=[-1])[:, tf.newaxis]\n + ps.range(c_in), shape=[-1])\n\n k = tf.gather(kernel, subkernel_ind, axis=-2)\n ind, shape = im2row_index(\n [eh, ew, c_in],\n block_shape=(fh_, fw_),\n slice_step=(1, 1),\n dilations=dilations)\n x_i = x_pad[..., :eh, :ew, :]\n x_i_shape = ps.shape(x_i)\n flat_shape = ps.pad(\n x_i_shape[:-3], paddings=[[0, 1]], constant_values=-1)\n flat_x = tf.reshape(x_i, flat_shape)\n x_ = tf.gather(flat_x, ind, axis=-1)\n im_x = tf.reshape(x_, ps.concat([x_i_shape[:-3], shape], axis=0))\n outputs = outputs.write(\n i,\n tf.matmul(\n im_x,\n tf.reshape(\n k, ps.concat(\n [kernel_batch, [1, fh_ * fw_* c_in, c_out]], axis=0)))\n )\n return i + 1, outputs\n\n outputs = tf.TensorArray(dtype=input_dtype, size=sh * sw)\n\n _, outputs = tf.while_loop(\n lambda i, _: i < sh * sw,\n loop_body,\n [0, outputs])\n\n y = outputs.concat()\n\n m = tf.reduce_prod(ps.shape(y)[:-3])\n y_ = tf.reshape(y, shape=ps.concat([[m], ps.shape(y)[-3:]], axis=0))\n y2 = tf.batch_to_space(\n y_, strides, crops=tf.zeros([2, 2], dtype=tf.int64))\n broadcast_batch_shape = ps.broadcast_shape(batch_shape, kernel_batch)\n y2 = tf.reshape(y2, ps.concat(\n [broadcast_batch_shape, ps.shape(y2)[-3:]], axis=0))\n\n out_height = _deconv_output_length(\n xh, filter_size=fh, padding=padding, output_padding=None,\n stride=sh, dilation=dh)\n out_width = _deconv_output_length(\n xw, filter_size=fw, padding=padding, output_padding=None,\n stride=sw, dilation=dw)\n\n return y2[..., truncate_top:truncate_top+out_height,\n truncate_left:truncate_left+out_width, :]\n return op\n\n\ndef _maybe_validate_input_shapes(\n kernel_shape, channels_in, filter_height, filter_width, validate_args):\n \"\"\"Validate shapes of inputs to convolution op.\"\"\"\n k_dim = kernel_shape[-2]\n k_dim_ = tf.get_static_value(k_dim)\n expected_k_dim = filter_height * filter_width * channels_in\n expected_k_dim_ = tf.get_static_value(expected_k_dim)\n assertions = []\n if expected_k_dim_ is not None and k_dim_ is not None:\n if expected_k_dim_ != k_dim_:\n raise ValueError(\n 'The size of the second-to-rightmost dimension of `kernel` ( ={}) '\n ' must equal `filter_height * filter_width * channels_in` ( ={}), '\n 'where `channels_in` is the size of the rightmost dimension of the '\n 'input.'.format(k_dim_, expected_k_dim_))\n elif validate_args:\n assertions.append(\n assert_util.assert_equal(\n k_dim, expected_k_dim,\n message=('The size of the second-to-rightmost dimension of `kernel`'\n ' must equal `filter_height * filter_width * channels_in`,'\n ' where `channels_in` is the size of the rightmost '\n 'dimension of the input.')))\n return assertions\n\n\ndef _get_transpose_conv_dilated_padding(filter_dim, stride, dilation, padding):\n \"\"\"Zero-padding for inputs dilated by strides.\"\"\"\n tot_filter_dim = filter_dim + (filter_dim - 1) * (dilation - 1)\n if padding == 'VALID':\n tot_pad = tot_filter_dim + stride - 2 + ps.maximum(\n tot_filter_dim - stride, 0)\n elif padding == 'SAME':\n tot_pad = tot_filter_dim + stride - 2\n return ps.cond(\n filter_dim >= stride,\n lambda: (tot_pad - tot_pad // 2 - stride + 1, tot_pad // 2),\n lambda: (filter_dim - stride, tot_pad - filter_dim + 1))\n\n\ndef _get_output_shape(rank, strides, padding, dilations, input_shape,\n output_size, filter_shape, output_padding=None):\n \"\"\"Compute the `output_shape` and `strides` arg used by `conv_transpose`.\"\"\"\n if output_padding is None:\n output_padding = (None,) * rank\n else:\n output_padding = utils.prepare_tuple_argument(\n output_padding, n=rank, arg_name='output_padding')\n for stride, out_pad in zip(strides, output_padding):\n if out_pad >= stride:\n raise ValueError('Stride {} must be greater than output '\n 'padding {}.'.format(strides, output_padding))\n event_shape = []\n for i in range(-rank, 0):\n event_shape.append(_deconv_output_length(\n input_shape[i - 1],\n filter_size=filter_shape[i],\n padding=padding,\n output_padding=output_padding[i],\n stride=strides[i],\n dilation=dilations[i]))\n event_shape.append(output_size)\n batch_shape = input_shape[:-rank-1]\n output_shape = ps.concat([batch_shape, event_shape], axis=0)\n strides = ps.pad(strides, paddings=[[1, 1]], constant_values=1)\n return output_shape, strides\n\n\ndef _deconv_output_length(input_size, filter_size, padding, output_padding,\n stride, dilation):\n \"\"\"Determines output length of a transposed convolution given input length.\n\n Args:\n input_size: `int`.\n filter_size: `int`.\n padding: one of `\"SAME\"`, `\"VALID\"`, `\"FULL\"`.\n output_padding: `int`, amount of padding along the output dimension. Can\n be set to `None` in which case the output length is inferred.\n stride: `int`.\n dilation: `int`.\n\n Returns:\n output_length: The output length (`int`).\n \"\"\"\n assert padding in {'SAME', 'VALID', 'FULL'}\n if input_size is None:\n return None\n # Get the dilated kernel size\n filter_size = filter_size + (filter_size - 1) * (dilation - 1)\n # Infer length if output padding is None, else compute the exact length\n if output_padding is None:\n if padding == 'VALID':\n return input_size * stride + ps.maximum(filter_size - stride, 0)\n elif padding == 'FULL':\n return input_size * stride - (stride + filter_size - 2)\n elif padding == 'SAME':\n return input_size * stride\n if padding == 'SAME':\n pad = filter_size // 2\n elif padding == 'VALID':\n pad = 0\n elif padding == 'FULL':\n pad = filter_size - 1\n return (input_size - 1) * stride + filter_size - 2 * pad + output_padding\n\n\ndef prepare_conv_args(\n filter_shape, rank, strides, padding, dilations,\n is_transpose=False, validate_args=False):\n \"\"\"Sanitizes use provided input.\"\"\"\n padding = _validate_padding(padding)\n try:\n rank = int(tf.get_static_value(rank))\n except TypeError:\n raise TypeError('Argument `rank` must be statically known `int`.')\n valid_rank = {1, 2, 3}\n if rank not in valid_rank:\n raise ValueError('Argument `rank` must be in {}.'.format(valid_rank))\n filter_shape = prepare_tuple_argument(\n filter_shape, n=rank, arg_name='filter_shape',\n validate_args=validate_args)\n strides = prepare_tuple_argument(\n strides, n=rank, arg_name='strides', validate_args=validate_args)\n padding = _prepare_padding_argument(padding)\n dilations = prepare_tuple_argument(\n dilations, n=rank, arg_name='dilations', validate_args=validate_args)\n\n strides_ = [tf.get_static_value(s) for s in strides]\n dilations_ = [tf.get_static_value(d) for d in dilations]\n assertions = []\n if is_transpose:\n if (all(s is not None for s in strides_)\n and all(d is not None for d in dilations_)):\n if any(s > 1 for s in strides_) and any(d > 1 for d in dilations_):\n raise NotImplementedError('At least one of `dilations` and `strides` '\n 'must equal `1` for each dimension. Saw: '\n '`strides={}`, `dilations={}`'.format(\n strides, dilations))\n elif validate_args:\n assertions.append(\n assert_util.assert_equal(\n tf.logical_or(\n tf.equal(tf.reduce_max(strides), 1),\n tf.equal(tf.reduce_max(dilations), 1)),\n True,\n message='At least one of `dilations` and `strides` must equal `1` '\n 'for each dimension.'))\n\n with tf.control_dependencies(assertions):\n return filter_shape, rank, strides, padding, dilations\n\n\ndef prepare_tuple_argument(arg, n, arg_name, validate_args=False):\n \"\"\"Helper which processes `Tensor`s to tuples in standard form.\"\"\"\n arg_size = ps.size(arg)\n arg_size_ = tf.get_static_value(arg_size)\n assertions = []\n if arg_size_ is not None:\n if arg_size_ not in (1, n):\n raise ValueError('The size of `{}` must be equal to `1` or to the rank '\n 'of the convolution (={}). Saw size = {}'.format(\n arg_name, n, arg_size_))\n elif validate_args:\n assertions.append(assert_util.assert_equal(\n ps.logical_or(arg_size == 1, arg_size == n),\n True,\n message=('The size of `{}` must be equal to `1` or to the rank of the '\n 'convolution (={})'.format(arg_name, n))))\n\n with tf.control_dependencies(assertions):\n arg = ps.broadcast_to(arg, shape=[n])\n arg = ps.unstack(arg, num=n)\n return arg\n\n\ndef _prepare_padding_argument(x):\n \"\"\"Helper which processes the padding argument.\"\"\"\n if not hasattr(x, 'upper'):\n return tuple(x)\n padding = x.upper()\n if padding in {'CAUSAL', 'FULL'}:\n raise NotImplementedError(\n 'Argument `padding` value \"{}\" currently not supported. If you '\n 'require this feature, please create an issue on '\n '`https://github.com/tensorflow/probability` or email '\n '`[email protected]`.'.format(padding))\n valid_values = {'VALID', 'SAME'}\n if padding not in valid_values:\n raise ValueError('Argument `padding` must be convertible to a tuple '\n 'or one of {}; saw: \"{}\".'.format(valid_values, padding))\n return padding\n\n\ndef _call_conv2d_transpose(x, kernel, filter_shape, strides, padding, dilations,\n c_out, batch_shape, event_shape):\n \"\"\"Call `tf.nn.conv2d_transpose` (for kernels with no batch dimensions).\"\"\"\n fh, fw = filter_shape\n flat_x = tf.reshape(x, shape=ps.concat([[-1], event_shape], axis=0))\n output_shape, strides_ = _get_output_shape(\n rank=2, strides=strides, padding=padding, dilations=dilations,\n input_shape=ps.shape(flat_x), output_size=c_out,\n filter_shape=filter_shape)\n flat_y = tf.nn.conv2d_transpose(\n flat_x,\n filters=tf.transpose(\n tf.reshape(\n kernel, shape=[fh, fw, event_shape[-1], -1]),\n perm=[0, 1, 3, 2]),\n output_shape=output_shape,\n strides=strides_,\n padding=padding,\n data_format='NHWC',\n dilations=dilations)\n return tf.reshape(\n flat_y, shape=ps.concat([batch_shape, output_shape[-3:]], axis=0))\n", "# Lint as: python3\n# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\nr\"\"\"Ground truth values for `german_credit_numeric_logistic_regression`.\n\nAutomatically generated using the command:\n\n```\npython -m inference_gym.tools.get_ground_truth \\\n --target \\\n german_credit_numeric_logistic_regression\n```\n\"\"\"\n\nimport numpy as np\n\nIDENTITY_MEAN = np.array([\n -0.7351048553686668,\n 0.41854235448568405,\n -0.4140361022849266,\n 0.12687262544490638,\n -0.36453584119271787,\n -0.1786990235929577,\n -0.1528721119830067,\n 0.0130935930161775,\n 0.18071618213137836,\n -0.11077840748059746,\n -0.22434837978228872,\n 0.12239538160879522,\n 0.028775849958589513,\n -0.13628208974727007,\n -0.29222110498210363,\n 0.2783575897857832,\n -0.2996277708109526,\n 0.30372734184257766,\n 0.27038791575592425,\n 0.12251564641333557,\n -0.062930540861664,\n -0.09271734036278598,\n -0.025386265018982113,\n -0.022952091856998594,\n -1.2033366774193333,\n]).reshape((25,))\n\nIDENTITY_MEAN_STANDARD_ERROR = np.array([\n 5.842293909946494e-05,\n 7.242951181494356e-05,\n 6.287678982885978e-05,\n 7.585193280148798e-05,\n 6.115211849593741e-05,\n 6.021116416974708e-05,\n 5.204191507761724e-05,\n 5.860998969304511e-05,\n 7.29503297927934e-05,\n 6.490239025755679e-05,\n 4.990373753354614e-05,\n 6.283413887066306e-05,\n 5.430645722326503e-05,\n 6.406386782855579e-05,\n 7.892840871425272e-05,\n 5.308342894035861e-05,\n 6.703376967839617e-05,\n 8.521129854167403e-05,\n 7.765561215475798e-05,\n 0.00010413139262019992,\n 0.00010841073917598099,\n 6.237296545620734e-05,\n 9.654815236395932e-05,\n 9.49005719330975e-05,\n 6.225181243823337e-05,\n]).reshape((25,))\n\nIDENTITY_STANDARD_DEVIATION = np.array([\n 0.0898313720177512,\n 0.10433392890125515,\n 0.09494358976312321,\n 0.10821559696336329,\n 0.09451801286114327,\n 0.09209986501802636,\n 0.08194570882231808,\n 0.09096249386093944,\n 0.10427142118193244,\n 0.09706664883314095,\n 0.07886872456716118,\n 0.09415178440121623,\n 0.08568162266412561,\n 0.094635647710843,\n 0.11794843143366165,\n 0.08278578466826157,\n 0.10338649406760281,\n 0.12112997506000497,\n 0.11129990766341216,\n 0.13748697192324197,\n 0.14311733514054628,\n 0.09036915198426924,\n 0.12757406812435373,\n 0.12488837996746398,\n 0.09189586059142167,\n]).reshape((25,))\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for the LKJ distribution.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow.compat.v1 as tf1\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_probability.python import distributions as tfd\nfrom tensorflow_probability.python.distributions.internal import statistical_testing as st\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import test_util\n\n\ndef _det_ok_mask(x, det_bounds, input_output_cholesky=False):\n if input_output_cholesky:\n logdet = 2.0 * tf.reduce_sum(\n tf.math.log(tf.linalg.diag_part(x)), axis=[-1])\n else:\n _, logdet = tf.linalg.slogdet(x)\n\n return tf.cast(tf.exp(logdet) > det_bounds, dtype=x.dtype)\n\n# Each leaf entry here is a confidence interval for the volume of some\n# set of correlation matrices. To wit, k-by-k correlation matrices\n# whose determinant is at least d appear as volume_bounds[k][d].\n# These particular confidence intervals were estimated by the\n# Clopper-Pearson method applied to 10^7 rejection samples, with an\n# error probability of 5e-7. This computation may be performed by\n# executing the correlation_matrix_volumes program with argument\n# --num_samples 1e7. Doing so took about 45 minutes on a standard\n# workstation.\nvolume_bounds = {\n 3: {0.01: (04.8334339757361420, 4.845866340472709),\n 0.25: (02.9993127232473036, 3.011629093880439),\n 0.30: (02.6791373340121916, 2.691146382760893),\n 0.35: (02.3763254004846030, 2.3879545568875358),\n 0.40: (02.0898224112869355, 2.1010041316917913),\n 0.45: (01.8202389505755674, 1.8309117190894892)},\n 4: {0.01: (10.983339932556953, 11.060156130783517),\n 0.25: (03.4305021152837020, 3.4764695469900464),\n 0.30: (02.6624323207206930, 2.703204389589173),\n 0.35: (02.0431263321809440, 2.0790437132708752),\n 0.40: (01.5447440594930320, 1.5761221057556805),\n 0.45: (01.1459065289947180, 1.1730410135527702)},\n 5: {0.01: (19.081135276668707, 19.523821224876603),\n 0.20: (02.8632254471072285, 3.0376848112309776),\n 0.25: (01.8225680180604158, 1.9623522646052605),\n 0.30: (01.1299612119639912, 1.2406126830051296),\n 0.35: (00.6871928383147943, 0.7740705901566753),\n 0.40: (00.4145900446719042, 0.482655106057178)}}\n\n\n@test_util.test_all_tf_execution_regimes\[email protected]_parameters(('_float32', np.float32),\n ('_float64', np.float64))\nclass LKJTest(test_util.TestCase):\n\n def testNormConst2D(self, dtype):\n expected = 2.\n # 2x2 correlation matrices are determined by one number between -1\n # and 1, so the volume of density 1 over all of them is 2.\n answer = self.evaluate(\n tfd.LKJ(2, dtype([1.]), validate_args=True)._log_normalization())\n self.assertAllClose(answer, np.log([expected]))\n\n def testNormConst3D(self, dtype):\n expected = np.pi**2 / 2.\n # 3x3 correlation matrices are determined by the three\n # lower-triangular entries. In addition to being between -1 and\n # 1, they must also obey the constraint that the determinant of\n # the resulting symmetric matrix is non-negative. The post\n # https://psychometroscar.com/the-volume-of-a-3-x-3-correlation-matrix/\n # derives (with elementary calculus) that the volume of this set\n # (with respect to Lebesgue^3 measure) is pi^2/2. The same result\n # is also obtained by Rousseeuw, P. J., & Molenberghs,\n # G. (1994). \"The shape of correlation matrices.\" The American\n # Statistician, 48(4), 276-279.\n answer = self.evaluate(\n tfd.LKJ(3, dtype([1.]), validate_args=True)._log_normalization())\n self.assertAllClose(answer, np.log([expected]))\n\n def _testSampleLogProbExact(self,\n concentrations,\n det_bounds,\n dim,\n means,\n num_samples=int(1e5),\n dtype=np.float32,\n target_discrepancy=0.1,\n input_output_cholesky=False,\n seed=42):\n # For test methodology see the comment in\n # _testSampleConsistentLogProbInterval, except that this test\n # checks those parameter settings where the true volume is known\n # analytically.\n concentration = np.array(concentrations, dtype=dtype)\n det_bounds = np.array(det_bounds, dtype=dtype)\n means = np.array(means, dtype=dtype)\n # Add a tolerance to guard against some of the importance_weights exceeding\n # the theoretical maximum (importance_maxima) due to numerical inaccuracies\n # while lower bounding the determinant. See corresponding comment in\n # _testSampleConsistentLogProbInterval.\n high_tolerance = 1e-6\n\n testee_lkj = tfd.LKJ(\n dimension=dim,\n concentration=concentration,\n input_output_cholesky=input_output_cholesky,\n validate_args=True)\n x = testee_lkj.sample(num_samples, seed=seed)\n importance_weights = (\n tf.exp(-testee_lkj.log_prob(x)) * _det_ok_mask(x, det_bounds,\n input_output_cholesky))\n importance_maxima = (1. / det_bounds) ** (concentration - 1) * tf.exp(\n testee_lkj._log_normalization())\n\n chk1 = st.assert_true_mean_equal_by_dkwm(\n importance_weights, low=0., high=importance_maxima + high_tolerance,\n expected=means, false_fail_rate=1e-6)\n chk2 = assert_util.assert_less(\n st.min_discrepancy_of_true_means_detectable_by_dkwm(\n num_samples,\n low=0.,\n high=importance_maxima + high_tolerance,\n false_fail_rate=1e-6,\n false_pass_rate=1e-6), dtype(target_discrepancy))\n self.evaluate([chk1, chk2])\n\n def testSampleConsistentLogProb2(self, dtype):\n concentrations = np.array([\n 1.00, 1.30, 1.50, 1.70, 1.90, 2.00, 2.10, 2.50, 3.00])\n det_bounds = np.array([\n 0.01, 0.25, 0.30, 0.40, 0.50, 0.50, 0.50, 0.70, 0.70])\n exact_volumes = 2 * np.sqrt(1. - det_bounds)\n\n for input_output_cholesky in [True, False]:\n self._testSampleLogProbExact(\n concentrations,\n det_bounds,\n 2,\n exact_volumes,\n num_samples=int(1.1e5),\n dtype=dtype,\n input_output_cholesky=input_output_cholesky,\n target_discrepancy=0.05,\n seed=test_util.test_seed())\n\n def _testSampleConsistentLogProbInterval(self,\n concentrations,\n det_bounds,\n dim,\n num_samples=int(1e5),\n dtype=np.float32,\n input_output_cholesky=False,\n false_fail_rate=1e-6,\n target_discrepancy=0.1,\n seed=42):\n # Consider the set M of dim x dim correlation matrices whose\n # determinant exceeds some bound (rationale for bound forthwith).\n # - This is a (convex!) shape in dim * (dim - 1) / 2 dimensions\n # (because a correlation matrix is determined by its lower\n # triangle, and the main diagonal is all 1s).\n # - Further, M is contained entirely in the [-1,1] cube,\n # because no correlation can fall outside that interval.\n #\n # We have two different ways to estimate the volume of M:\n # - Importance sampling from the LKJ distribution\n # - Importance sampling from the uniform distribution on the cube\n #\n # This test checks that these two methods agree. However, because\n # the uniform proposal leads to many rejections (thus slowness),\n # those volumes are computed offline and the confidence intervals\n # are presented to this test procedure in the \"volume_bounds\"\n # table.\n #\n # Why place a lower bound on the determinant? Because for eta > 1,\n # the density of LKJ approaches 0 as the determinant approaches 0.\n # However, the test methodology requires an upper bound on the\n # improtance weights produced. Rejecting matrices with too-small\n # determinant (from both methods) allows me to supply that bound.\n #\n # I considered several alternative regions whose volume I might\n # know analytically (without having to do rejection).\n # - Option a: Some hypersphere guaranteed to be contained inside M.\n # - Con: I don't know a priori how to find a radius for it.\n # - Con: I still need a lower bound on the determinants that appear\n # in this sphere, and I don't know how to compute it.\n # - Option b: Some trapezoid given as the convex hull of the\n # nearly-extreme correlation matrices (i.e., those that partition\n # the variables into two strongly anti-correclated groups).\n # - Con: Would have to dig up n-d convex hull code to implement this.\n # - Con: Need to compute the volume of that convex hull.\n # - Con: Need a bound on the determinants of the matrices in that hull.\n # - Option c: Same thing, but with the matrices that make a single pair\n # of variables strongly correlated (or anti-correlated), and leaves\n # the others uncorrelated.\n # - Same cons, except that there is a determinant bound (which\n # felt pretty loose).\n lows = [dtype(volume_bounds[dim][db][0]) for db in det_bounds]\n highs = [dtype(volume_bounds[dim][db][1]) for db in det_bounds]\n concentration = np.array(concentrations, dtype=dtype)\n det_bounds = np.array(det_bounds, dtype=dtype)\n # Due to possible numerical inaccuracies while lower bounding the\n # determinant, the maximum of the importance weights may exceed the\n # theoretical maximum (importance_maxima). We add a tolerance to guard\n # against this. An alternative would have been to add a threshold while\n # filtering in _det_ok_mask, but that would affect the mean as well.\n high_tolerance = 1e-6\n\n testee_lkj = tfd.LKJ(\n dimension=dim,\n concentration=concentration,\n input_output_cholesky=input_output_cholesky,\n validate_args=True)\n x = testee_lkj.sample(num_samples, seed=seed)\n importance_weights = (\n tf.exp(-testee_lkj.log_prob(x)) * _det_ok_mask(x, det_bounds,\n input_output_cholesky))\n importance_maxima = (1. / det_bounds) ** (concentration - 1) * tf.exp(\n testee_lkj._log_normalization())\n check1 = st.assert_true_mean_in_interval_by_dkwm(\n samples=importance_weights,\n low=0.,\n high=importance_maxima + high_tolerance,\n expected_low=lows,\n expected_high=highs,\n false_fail_rate=false_fail_rate)\n check2 = assert_util.assert_less(\n st.min_discrepancy_of_true_means_detectable_by_dkwm(\n num_samples,\n low=0.,\n high=importance_maxima + high_tolerance,\n false_fail_rate=false_fail_rate,\n false_pass_rate=false_fail_rate), dtype(target_discrepancy))\n self.evaluate([check1, check2])\n\n def testSampleConsistentLogProbInterval3(self, dtype):\n # The hardcoded volume boundaries are (5e-7)-confidence intervals\n # of a rejection sampling run. Ergo, I only have 5e-7 probability\n # mass left for the false fail rate of the test so the aggregate\n # false fail probability is 1e-6.\n concentrations = [\n 1.00, 1.30, 1.50, 1.70, 1.90, 2.00, 2.10, 2.50, 3.00]\n det_bounds = [\n 0.01, 0.25, 0.25, 0.30, 0.35, 0.35, 0.35, 0.40, 0.45]\n\n for input_output_cholesky in [True, False]:\n self._testSampleConsistentLogProbInterval(\n concentrations,\n det_bounds,\n 3,\n dtype=dtype,\n input_output_cholesky=input_output_cholesky,\n false_fail_rate=5e-7,\n target_discrepancy=0.11,\n seed=test_util.test_seed())\n\n def testSampleConsistentLogProbInterval4(self, dtype):\n # The hardcoded volume boundaries are (5e-7)-confidence intervals\n # of a rejection sampling run. Ergo, I only have 5e-7 probability\n # mass left for the false fail rate of the test so the aggregate\n # false fail probability is 1e-6.\n concentrations = [\n 1.00, 1.30, 1.50, 1.70, 1.90, 2.00, 2.10, 2.50, 3.00]\n det_bounds = [\n 0.01, 0.25, 0.25, 0.30, 0.35, 0.35, 0.35, 0.40, 0.45]\n for input_output_cholesky in [True, False]:\n self._testSampleConsistentLogProbInterval(\n concentrations,\n det_bounds,\n 4,\n dtype=dtype,\n input_output_cholesky=input_output_cholesky,\n false_fail_rate=5e-7,\n target_discrepancy=0.22,\n seed=test_util.test_seed())\n\n def testSampleConsistentLogProbInterval5(self, dtype):\n # The hardcoded volume boundaries are (5e-7)-confidence intervals\n # of a rejection sampling run. Ergo, I only have 5e-7 probability\n # mass left for the false fail rate of the test so the aggregate\n # false fail probability is 1e-6.\n concentrations = [\n 1.00, 1.30, 1.50, 1.70, 1.90, 2.00, 2.10, 2.50, 3.00]\n det_bounds = [\n 0.01, 0.20, 0.20, 0.25, 0.30, 0.30, 0.30, 0.35, 0.40]\n\n for input_output_cholesky in [True, False]:\n self._testSampleConsistentLogProbInterval(\n concentrations,\n det_bounds,\n 5,\n dtype=dtype,\n input_output_cholesky=input_output_cholesky,\n false_fail_rate=5e-7,\n target_discrepancy=0.41,\n seed=test_util.test_seed())\n\n def testDimensionGuard(self, dtype):\n testee_lkj = tfd.LKJ(\n dimension=3, concentration=dtype([1., 4.]), validate_args=True)\n with self.assertRaisesRegexp(ValueError, 'dimension mismatch'):\n testee_lkj.log_prob(dtype(np.eye(4)))\n\n def testAssertValidCorrelationMatrix(self, dtype):\n lkj = tfd.LKJ(\n dimension=2, concentration=dtype([1., 4.]), validate_args=True)\n with self.assertRaisesOpError('Correlations must be >= -1.'):\n self.evaluate(lkj.log_prob(dtype([[1., -1.3], [-1.3, 1.]])))\n with self.assertRaisesOpError('Correlations must be <= 1.'):\n self.evaluate(lkj.log_prob(dtype([[1., 1.3], [1.3, 1.]])))\n with self.assertRaisesOpError('Self-correlations must be = 1.'):\n self.evaluate(lkj.log_prob(dtype([[0.5, 0.5], [0.5, 1.]])))\n with self.assertRaisesOpError('Correlation matrices must be symmetric.'):\n self.evaluate(lkj.log_prob(dtype([[1., 0.2], [0.3, 1.]])))\n\n def testZeroDimension(self, dtype):\n testee_lkj = tfd.LKJ(\n dimension=0, concentration=dtype([1., 4.]), validate_args=True)\n results = testee_lkj.sample(sample_shape=[4, 3], seed=test_util.test_seed())\n self.assertEqual(results.shape, [4, 3, 2, 0, 0])\n\n def testOneDimension(self, dtype):\n testee_lkj = tfd.LKJ(\n dimension=1, concentration=dtype([1., 4.]), validate_args=True)\n results = testee_lkj.sample(sample_shape=[4, 3], seed=test_util.test_seed())\n self.assertEqual(results.shape, [4, 3, 2, 1, 1])\n\n def testMean(self, dtype):\n testee_lkj = tfd.LKJ(\n dimension=3, concentration=dtype([1., 3., 5.]), validate_args=True)\n num_samples = 20000\n results = testee_lkj.sample(\n sample_shape=[num_samples], seed=test_util.test_seed())\n mean = testee_lkj.mean()\n self.assertEqual(mean.shape, [3, 3, 3])\n # tfd.LKJ has some small numerical issues, so we allow for some amount of\n # numerical tolerance when testing means.\n numerical_tolerance = 1e-5\n check1 = st.assert_true_mean_in_interval_by_dkwm(\n samples=results, low=-1., high=1.,\n expected_low=mean - numerical_tolerance,\n expected_high=mean + numerical_tolerance,\n false_fail_rate=1e-6)\n check2 = assert_util.assert_less(\n st.min_discrepancy_of_true_means_detectable_by_dkwm(\n num_samples,\n low=-1.,\n high=1.,\n # Smaller false fail rate because of different batch sizes between\n # these two checks.\n false_fail_rate=1e-7,\n false_pass_rate=1e-6),\n # 4% relative error\n 0.08)\n self.evaluate([check1, check2])\n\n def testMeanHigherDimension(self, dtype):\n testee_lkj = tfd.LKJ(\n dimension=6, concentration=dtype([1., 3., 5.]), validate_args=True)\n num_samples = 20000\n results = testee_lkj.sample(\n sample_shape=[num_samples], seed=test_util.test_seed())\n mean = testee_lkj.mean()\n self.assertEqual(mean.shape, [3, 6, 6])\n # tfd.LKJ has some small numerical issues, so we allow for some amount of\n # numerical tolerance when testing means.\n numerical_tolerance = 1e-5\n check1 = st.assert_true_mean_in_interval_by_dkwm(\n samples=results, low=-1., high=1.,\n expected_low=mean - numerical_tolerance,\n expected_high=mean + numerical_tolerance,\n false_fail_rate=1e-6)\n check2 = assert_util.assert_less(\n st.min_discrepancy_of_true_means_detectable_by_dkwm(\n num_samples,\n low=-1.,\n high=1.,\n # Smaller false fail rate because of different batch sizes between\n # these two checks.\n false_fail_rate=1e-7,\n false_pass_rate=1e-6),\n # 4% relative error\n 0.08)\n self.evaluate([check1, check2])\n\n def testValidateConcentration(self, dtype):\n dimension = 3\n concentration = tf.Variable(0.5, dtype=dtype)\n d = tfd.LKJ(dimension, concentration, validate_args=True)\n with self.assertRaisesOpError('Argument `concentration` must be >= 1.'):\n self.evaluate([v.initializer for v in d.variables])\n self.evaluate(d.sample(seed=test_util.test_seed()))\n\n def testValidateConcentrationAfterMutation(self, dtype):\n dimension = 3\n concentration = tf.Variable(1.5, dtype=dtype)\n d = tfd.LKJ(dimension, concentration, validate_args=True)\n self.evaluate([v.initializer for v in d.variables])\n with self.assertRaisesOpError('Argument `concentration` must be >= 1.'):\n with tf.control_dependencies([concentration.assign(0.5)]):\n self.evaluate(d.mean())\n\n def testDefaultEventSpaceBijectorValidCorrelation(self, dtype):\n d = tfd.LKJ(3, tf.constant(1., dtype), validate_args=True)\n b = d.experimental_default_event_space_bijector()\n sample = b(tf.zeros((3, 3), dtype))\n self.evaluate(d.log_prob(sample))\n\n\nclass LKJTestGraphOnly(test_util.TestCase):\n\n def testDimensionGuardDynamicShape(self):\n if tf.executing_eagerly():\n return\n testee_lkj = tfd.LKJ(\n dimension=3, concentration=[1., 4.], validate_args=True)\n with self.assertRaisesOpError('dimension mismatch'):\n self.evaluate(\n testee_lkj.log_prob(\n tf1.placeholder_with_default(tf.eye(4), shape=None)))\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for RQ Spline bijector.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\n\nimport hypothesis as hp\nfrom hypothesis import strategies as hps\nimport numpy as np\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python import bijectors as tfb\nfrom tensorflow_probability.python.bijectors import bijector_test_util\nfrom tensorflow_probability.python.bijectors import hypothesis_testlib as bijector_hps\nfrom tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps\nfrom tensorflow_probability.python.internal import prefer_static as ps\nfrom tensorflow_probability.python.internal import test_util\n\n\nJAX_MODE = False\n\n# pylint: disable=no-value-for-parameter\n\n\[email protected]\ndef rq_splines(draw, batch_shape=None, dtype=tf.float32):\n if batch_shape is None:\n batch_shape = draw(tfp_hps.shapes())\n\n lo = draw(hps.floats(min_value=-5, max_value=.5))\n hi = draw(hps.floats(min_value=-.5, max_value=5))\n lo, hi = min(lo, hi), max(lo, hi) + .2\n hp.note('lo, hi: {!r}'.format((lo, hi)))\n\n constraints = dict(\n bin_widths=functools.partial(\n bijector_hps.spline_bin_size_constraint, hi=hi, lo=lo, dtype=dtype),\n bin_heights=functools.partial(\n bijector_hps.spline_bin_size_constraint, hi=hi, lo=lo, dtype=dtype),\n knot_slopes=functools.partial(\n bijector_hps.spline_slope_constraint, dtype=dtype))\n params = draw(\n tfp_hps.broadcasting_params(\n batch_shape,\n params_event_ndims=dict(bin_widths=1, bin_heights=1, knot_slopes=1),\n constraint_fn_for=constraints.get))\n hp.note('params: {!r}'.format(params))\n return tfb.RationalQuadraticSpline(\n range_min=lo, validate_args=draw(hps.booleans()), **params)\n\n\n@test_util.test_all_tf_execution_regimes\nclass RationalQuadraticSplineTest(test_util.TestCase):\n\n @test_util.disable_test_for_backend(\n disable_numpy=True, disable_jax=True,\n reason='tfb.RealNVP not exposed in JAX and Numpy backend.')\n def testDocExample(self):\n\n nsplits = 3\n\n class SplineParams(tf.Module):\n\n def __init__(self, nbins=32):\n self._nbins = nbins\n self._built = False\n self._bin_widths = None\n self._bin_heights = None\n self._knot_slopes = None\n\n def __call__(self, x, nunits):\n if not self._built:\n def _bin_positions(x):\n out_shape = ps.concat((ps.shape(x)[:-1], (nunits, self._nbins)), 0)\n x = tf.reshape(x, out_shape)\n return tf.math.softmax(x, axis=-1) * (2 - self._nbins * 1e-2) + 1e-2\n\n def _slopes(x):\n out_shape = tf.concat((\n ps.shape(x)[:-1], (nunits, self._nbins - 1)), 0)\n x = tf.reshape(x, out_shape)\n return tf.math.softplus(x) + 1e-2\n\n self._bin_widths = tf.keras.layers.Dense(\n nunits * self._nbins, activation=_bin_positions, name='w')\n self._bin_heights = tf.keras.layers.Dense(\n nunits * self._nbins, activation=_bin_positions, name='h')\n self._knot_slopes = tf.keras.layers.Dense(\n nunits * (self._nbins - 1), activation=_slopes, name='s')\n self._built = True\n\n return tfb.RationalQuadraticSpline(\n bin_widths=self._bin_widths(x),\n bin_heights=self._bin_heights(x),\n knot_slopes=self._knot_slopes(x))\n\n xs = np.random.randn(3, 15).astype(np.float32) # Keras won't Dense(.)(vec).\n splines = [SplineParams() for _ in range(nsplits)]\n\n def spline_flow():\n stack = tfb.Identity()\n for i in range(nsplits):\n stack = tfb.RealNVP(5 * i, bijector_fn=splines[i])(stack)\n return stack\n\n ys = spline_flow().forward(xs)\n ys_inv = spline_flow().inverse(ys) # reconstruct ensures no cache hit.\n\n init_vars = []\n for s in splines:\n init_vars += [v.initializer for v in s.variables]\n self.evaluate(init_vars)\n self.assertAllClose(xs, self.evaluate(ys_inv))\n\n def testDegenerateSplines(self):\n bijector = tfb.RationalQuadraticSpline([], [], 1, validate_args=True)\n xs = np.linspace(-2, 2, 20, dtype=np.float32)\n self.assertAllClose(xs, self.evaluate(bijector.forward(xs)))\n self.assertAllClose(\n 0, self.evaluate(bijector.forward_log_det_jacobian(xs, event_ndims=1)))\n self.assertAllClose(\n np.zeros_like(xs),\n self.evaluate(bijector.forward_log_det_jacobian(xs, event_ndims=0)))\n\n bijector = tfb.RationalQuadraticSpline([2.], [2.], [], validate_args=True)\n xs = np.linspace(-2, 2, 20, dtype=np.float32)\n self.assertAllClose(xs, self.evaluate(bijector.forward(xs)))\n self.assertAllClose(\n 0, self.evaluate(bijector.forward_log_det_jacobian(xs, event_ndims=1)))\n self.assertAllClose(\n np.zeros_like(xs),\n self.evaluate(bijector.forward_log_det_jacobian(xs, event_ndims=0)))\n\n def testTheoreticalFldjSimple(self):\n bijector = tfb.RationalQuadraticSpline(\n bin_widths=[1., 1],\n bin_heights=[np.sqrt(.5), 2 - np.sqrt(.5)],\n knot_slopes=1)\n self.assertEqual(tf.float64, bijector.dtype)\n dim = 5\n x = np.linspace(-1.05, 1.05, num=2 * dim, dtype=np.float64).reshape(2, dim)\n y = self.evaluate(bijector.forward(x))\n bijector_test_util.assert_bijective_and_finite(\n bijector,\n x,\n y,\n eval_func=self.evaluate,\n event_ndims=0,\n inverse_event_ndims=0,\n rtol=1e-5)\n fldj = bijector.forward_log_det_jacobian(x, event_ndims=0)\n fldj_theoretical = bijector_test_util.get_fldj_theoretical(\n bijector, x, event_ndims=0)\n self.assertAllClose(\n self.evaluate(fldj_theoretical),\n self.evaluate(fldj),\n atol=1e-5,\n rtol=1e-5)\n\n @test_util.numpy_disable_gradient_test\n @hp.given(hps.data())\n @tfp_hps.tfp_hp_settings(default_max_examples=5)\n def testTheoreticalFldj(self, data):\n if not tf.executing_eagerly():\n msg = ('Testing eager mode only because graph is very slow, '\n 'presumably due to costly graph construction.')\n self.skipTest(msg)\n if JAX_MODE: # TODO(b/160167257): Eliminate this workaround.\n # get_fldj_theoretical uses tfp.math.batch_jacobian and assumes the\n # behavior of the bijector does not vary by position. In this case, it\n # can, so we must vmap the result.\n batch_shape = [1]\n else:\n # get_fldj_theoretical test rig requires 1-d batches.\n batch_shape = data.draw(tfp_hps.shapes(min_ndims=1, max_ndims=1))\n hp.note('batch shape: {}'.format(batch_shape))\n bijector = data.draw(rq_splines(batch_shape=batch_shape, dtype=tf.float64))\n self.assertEqual(tf.float64, bijector.dtype)\n bw, bh, kd = self.evaluate(\n [bijector.bin_widths, bijector.bin_heights, bijector.knot_slopes])\n hp.note('bw: {!r}\\nbh: {!r}\\nkd: {!r}'.format(bw, bh, kd))\n x_shp = ((bw + bh)[..., :-1] + kd).shape[:-1]\n if x_shp[-1] == 1: # Possibly broadcast the x dim.\n dim = data.draw(hps.integers(min_value=1, max_value=7))\n x_shp = x_shp[:-1] + (dim,)\n x = np.linspace(-4.9, 4.9, np.prod(x_shp), dtype=np.float64).reshape(*x_shp)\n hp.note('x: {!r}'.format(x))\n y = self.evaluate(bijector.forward(x))\n hp.note('x: {!r}'.format(x))\n bijector_test_util.assert_bijective_and_finite(\n bijector,\n x,\n y,\n eval_func=self.evaluate,\n event_ndims=0,\n inverse_event_ndims=0,\n rtol=1e-5)\n fldj = bijector.forward_log_det_jacobian(x, event_ndims=0)\n fldj_theoretical = bijector_test_util.get_fldj_theoretical(\n bijector, x, event_ndims=0)\n self.assertAllClose(\n self.evaluate(fldj_theoretical),\n self.evaluate(fldj),\n atol=1e-5,\n rtol=1e-5)\n\n def testVerifiesBroadcastingStatic(self):\n with self.assertRaisesRegex(ValueError, '`bin_heights` must broadcast'):\n tfb.RationalQuadraticSpline([[2, 1, .5]] * 2, [[.5, 2, 1]] * 3, [.3, 2])\n\n with self.assertRaisesRegex(ValueError,\n 'non-scalar `knot_slopes` must broadcast'):\n tfb.RationalQuadraticSpline([2, 1, .5], [.5, 2, 1], [.3, 2, .5])\n\n @test_util.disable_test_for_backend(\n disable_numpy=True, disable_jax=True,\n reason='Shapes are static in JAX and numpy backend.')\n def testVerifiesBroadcastingDynamic(self):\n\n @tf.function\n def f(bin_sizes, slopes):\n return tfb.RationalQuadraticSpline(\n bin_sizes, bin_sizes, slopes, validate_args=True).forward(bin_sizes)\n\n f = f.get_concrete_function(\n tf.TensorSpec((None,), dtype=tf.float32),\n tf.TensorSpec((None,), dtype=tf.float32))\n\n with self.assertRaisesOpError('Incompatible shapes'):\n self.evaluate(f(tf.constant([1., 1, 1, 1]), tf.constant([2., 3])))\n\n def testAssertsMismatchedSums(self):\n with self.assertRaisesOpError(r'`sum\\(bin_widths, axis=-1\\)` must equal '\n r'`sum\\(bin_heights, axis=-1\\)`'):\n bijector = tfb.RationalQuadraticSpline(\n bin_widths=[.2, .1, .5],\n bin_heights=[.1, .3, 5.4],\n knot_slopes=[.3, .5],\n validate_args=True)\n self.evaluate(bijector.forward([.3]))\n\n def testAssertsNonPositiveBinSizes(self):\n with self.assertRaisesOpError('`bin_widths` must be positive'):\n bijector = tfb.RationalQuadraticSpline(\n bin_widths=[.3, .2, -.1],\n bin_heights=[.1, .2, .1],\n knot_slopes=[.4, .5],\n validate_args=True)\n self.evaluate(bijector.forward([.3]))\n\n with self.assertRaisesOpError('`bin_heights` must be positive'):\n bijector = tfb.RationalQuadraticSpline(\n bin_widths=[.3, .2, .1],\n bin_heights=[.5, 0, .1],\n knot_slopes=[.3, .7],\n validate_args=True)\n self.evaluate(bijector.forward([.3]))\n\n def testAssertsNonPositiveSlope(self):\n with self.assertRaisesOpError('`knot_slopes` must be positive'):\n bijector = tfb.RationalQuadraticSpline(\n bin_widths=[.1, .2, 1],\n bin_heights=[1, .2, .1],\n knot_slopes=[-.5, 1],\n validate_args=True)\n self.evaluate(bijector.forward([.3]))\n\n with self.assertRaisesOpError('`knot_slopes` must be positive'):\n bijector = tfb.RationalQuadraticSpline(\n bin_widths=[.1, .2, 1],\n bin_heights=[1, .2, .1],\n knot_slopes=[1, 0.],\n validate_args=True)\n self.evaluate(bijector.forward([.3]))\n\n\nif __name__ == '__main__':\n tf.enable_v2_behavior()\n tf.test.main()\n", "# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for special.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\n\nfrom absl.testing import parameterized\nimport numpy as np\nfrom scipy import constants as scipy_constants\nfrom scipy import special as scipy_special\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\n\nfrom tensorflow_probability.python import math as tfp_math\nfrom tensorflow_probability.python.internal import test_util\nfrom tensorflow_probability.python.math.bessel import _compute_general_continued_fraction\n\n\n@test_util.test_all_tf_execution_regimes\nclass BesselIvRatioTest(test_util.TestCase):\n\n def testContinuedFraction(self):\n # Check that the simplest continued fraction returns the golden ratio.\n self.assertAllClose(\n self.evaluate(\n _compute_general_continued_fraction(\n 100, [], partial_numerator_fn=lambda _: 1.)),\n scipy_constants.golden - 1.)\n\n # Check the continued fraction constant is returned.\n cf_constant_denominators = scipy_special.i1(2.) / scipy_special.i0(2.)\n\n self.assertAllClose(\n self.evaluate(\n _compute_general_continued_fraction(\n 100,\n [],\n partial_denominator_fn=lambda i: i,\n tolerance=1e-5)),\n cf_constant_denominators, rtol=1e-5)\n\n cf_constant_numerators = np.sqrt(2 / (np.e * np.pi)) / (\n scipy_special.erfc(np.sqrt(0.5))) - 1.\n\n # Check that we can specify dtype and tolerance.\n self.assertAllClose(\n self.evaluate(\n _compute_general_continued_fraction(\n 100, [], partial_numerator_fn=lambda i: i,\n tolerance=1e-5,\n dtype=tf.float64)),\n cf_constant_numerators, rtol=1e-5)\n\n def VerifyBesselIvRatio(self, v, z, rtol):\n bessel_iv_ratio, v, z = self.evaluate([\n tfp.math.bessel_iv_ratio(v, z), v, z])\n # Use ive to avoid nans.\n scipy_ratio = scipy_special.ive(v, z) / scipy_special.ive(v - 1., z)\n self.assertAllClose(bessel_iv_ratio, scipy_ratio, rtol=rtol)\n\n def testBesselIvRatioVAndZSmall(self):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], seed=seed_stream())\n v = tf.random.uniform([int(1e5)], seed=seed_stream())\n # When both values are small, both the scipy ratio and\n # the computation become numerically unstable.\n # Anecdotally (when comparing to mpmath) the computation is more often\n # 'right' compared to the naive ratio.\n\n bessel_iv_ratio, v, z = self.evaluate([\n tfp.math.bessel_iv_ratio(v, z), v, z])\n scipy_ratio = scipy_special.ive(v, z) / scipy_special.ive(v - 1., z)\n\n safe_scipy_values = np.where(\n ~np.isnan(scipy_ratio) & (scipy_ratio != 0.))\n\n self.assertAllClose(\n bessel_iv_ratio[safe_scipy_values],\n scipy_ratio[safe_scipy_values], rtol=3e-4, atol=1e-6)\n\n def testBesselIvRatioVAndZMedium(self):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream())\n v = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream())\n self.VerifyBesselIvRatio(v, z, rtol=7e-6)\n\n def testBesselIvRatioVAndZLarge(self):\n seed_stream = test_util.test_seed_stream()\n # Use 50 as a cap. It's been observed that for v > 50, that\n # the scipy ratio can be quite wrong compared to mpmath.\n z = tf.random.uniform([int(1e5)], 10., 50., seed=seed_stream())\n v = tf.random.uniform([int(1e5)], 10., 50., seed=seed_stream())\n\n # For large v, z, scipy can return NaN values. Filter those out.\n bessel_iv_ratio, v, z = self.evaluate([\n tfp.math.bessel_iv_ratio(v, z), v, z])\n # Use ive to avoid nans.\n scipy_ratio = scipy_special.ive(v, z) / scipy_special.ive(v - 1., z)\n # Exclude zeros and NaN's from scipy. This can happen because the\n # individual function computations may zero out, and thus cause issues\n # in the ratio.\n safe_scipy_values = np.where(\n ~np.isnan(scipy_ratio) & (scipy_ratio != 0.))\n\n self.assertAllClose(\n bessel_iv_ratio[safe_scipy_values],\n scipy_ratio[safe_scipy_values],\n # We need to set a high rtol as the scipy computation is numerically\n # unstable.\n rtol=1e-6)\n\n def testBesselIvRatioVLessThanZ(self):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream())\n # Make v randomly less than z\n v = z * tf.random.uniform([int(1e5)], 0.1, 0.5, seed=seed_stream())\n self.VerifyBesselIvRatio(v, z, rtol=6e-6)\n\n def testBesselIvRatioVGreaterThanZ(self):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream())\n # Make z randomly less than v\n z = v * tf.random.uniform([int(1e5)], 0.1, 0.5, seed=seed_stream())\n self.VerifyBesselIvRatio(v, z, rtol=1e-6)\n\n @test_util.numpy_disable_gradient_test\n def testBesselIvRatioGradient(self):\n v = tf.constant([0.5, 1., 10., 20.])[..., tf.newaxis]\n x = tf.constant([0.1, 0.5, 0.9, 1., 12., 14., 22.])\n\n err = self.compute_max_gradient_error(\n functools.partial(tfp_math.bessel_iv_ratio, v), [x])\n self.assertLess(err, 2e-4)\n\n\n@test_util.test_all_tf_execution_regimes\nclass BesselIveTest(test_util.TestCase):\n\n def VerifyBesselIve(self, v, z, rtol, atol=1e-7):\n bessel_ive, v, z = self.evaluate([\n tfp.math.bessel_ive(v, z), v, z])\n scipy_ive = scipy_special.ive(v, z)\n self.assertAllClose(bessel_ive, scipy_ive, rtol=rtol, atol=atol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32),\n (\"float64\", np.float64),\n )\n def testBesselIveAtZero(self, dtype):\n # Check that z = 0 returns 1 for v = 0 and 0 otherwise.\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform([10], 1., 10., seed=seed_stream(), dtype=dtype)\n z = tf.constant(0., dtype=dtype)\n self.assertAllClose(\n self.evaluate(tfp.math.bessel_ive(v, z)),\n np.zeros([10], dtype=dtype))\n\n v = tf.constant([0.], dtype=dtype)\n self.assertAllClose(\n self.evaluate(tfp.math.bessel_ive(v, z)),\n np.ones([1], dtype=dtype))\n\n @parameterized.named_parameters(\n (\"float32\", np.float32),\n (\"float64\", np.float64),\n )\n def testBesselIveZNegativeNaN(self, dtype):\n # Check that z < 0 returns NaN for non-integer v.\n seed_stream = test_util.test_seed_stream()\n v = np.linspace(1.1, 10.2, num=11, dtype=dtype)\n z = tf.random.uniform([11], -10., -1., seed=seed_stream(), dtype=dtype)\n bessel_ive = self.evaluate(tfp.math.bessel_ive(v, z))\n self.assertTrue(np.all(np.isnan(bessel_ive)))\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveZNegativeVInteger(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = np.linspace(1., 10., num=10, dtype=dtype)\n z = tf.random.uniform([10], -10., -1., seed=seed_stream(), dtype=dtype)\n z, bessel_ive = self.evaluate([z, tfp.math.bessel_ive(v, z)])\n scipy_ive = scipy_special.ive(v, z)\n self.assertAllClose(bessel_ive, scipy_ive, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveZNegativeVLarge(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = np.linspace(100., 200., num=10, dtype=dtype)\n z = tf.random.uniform([10], -10., -1., seed=seed_stream(), dtype=dtype)\n z, bessel_ive = self.evaluate([z, tfp.math.bessel_ive(v, z)])\n scipy_ive = scipy_special.ive(v, z)\n self.assertAllClose(bessel_ive, scipy_ive, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1.5e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveVAndZSmall(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform([int(1e5)], seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 3e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveZTiny(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform(\n [int(1e5)], 1e-13, 1e-6, seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform([int(1e5)], 0., 10., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol, atol=1e-7)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 7e-6),\n (\"float64\", np.float64, 6e-6),\n )\n def testBesselIveVAndZMedium(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveVAndZLarge(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 10., 50., seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform([int(1e5)], 10., 50., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveVAndZVeryLarge(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform(\n [int(1e5)], 50., 100., seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform(\n [int(1e5)], 50., 100., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 7e-6),\n (\"float64\", np.float64, 7e-6),\n )\n def testBesselIveVLessThanZ(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n # Make v randomly less than z\n v = z * tf.random.uniform(\n [int(1e5)], 0.1, 0.5, seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveVGreaterThanZ(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n # Make z randomly less than v\n z = v * tf.random.uniform(\n [int(1e5)], 0.1, 0.5, seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-4),\n (\"float64\", np.float64, 7e-6),\n )\n def testBesselIveVNegative(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform(\n [int(1e5)], -10., -1., seed=seed_stream(), dtype=dtype)\n z = tf.random.uniform([int(1e5)], 1., 15., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveVZero(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.constant(0., dtype=dtype)\n z = tf.random.uniform([int(1e5)], 1., 15., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselIveLargeZ(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform(\n [int(1e5)], minval=0., maxval=0.5, seed=seed_stream(), dtype=dtype)\n z = tf.random.uniform(\n [int(1e5)], minval=100., maxval=10000., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselIve(v, z, rtol=rtol)\n\n @test_util.numpy_disable_gradient_test\n @parameterized.named_parameters(\n (\"float32\", np.float32),\n (\"float64\", np.float64))\n def testBesselIveGradient(self, dtype):\n v = tf.constant([-1., 0.5, 1., 10., 20.], dtype=dtype)[..., tf.newaxis]\n z = tf.constant([0.2, 0.5, 0.9, 1., 12., 14., 22.], dtype=dtype)\n\n err = self.compute_max_gradient_error(\n functools.partial(tfp_math.bessel_ive, v), [z])\n self.assertLess(err, 2e-4)\n\n @test_util.numpy_disable_gradient_test\n @parameterized.named_parameters(\n (\"float32\", np.float32),\n (\"float64\", np.float64))\n def testBesselIveNegativeGradient(self, dtype):\n v = tf.constant([1., 10., 20.], dtype=dtype)[..., tf.newaxis]\n z = tf.constant([-.2, -2.5, -3.5, -5.], dtype=dtype)\n\n err = self.compute_max_gradient_error(\n functools.partial(tfp_math.bessel_ive, v), [z])\n self.assertLess(err, 2e-4)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testLogBesselIveCorrect(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform(\n [int(1e5)], minval=0.1, maxval=0.5, seed=seed_stream(), dtype=dtype)\n z = tf.random.uniform(\n [int(1e5)], minval=1., maxval=10., seed=seed_stream(), dtype=dtype)\n _, _, log_bessel_ive_expected_, log_bessel_ive_actual_ = self.evaluate([\n v,\n z,\n tf.math.log(tfp.math.bessel_ive(v, z)),\n tfp.math.log_bessel_ive(v, z)])\n self.assertAllClose(\n log_bessel_ive_expected_, log_bessel_ive_actual_, rtol=rtol)\n\n def testLogBesselIveTestNonInf(self):\n # Test that log_bessel_ive(v, z) has more resolution than simply computing\n # log(bessel_ive(v, z)). The inputs below will return -inf in naive float64\n # computation.\n v = np.array([10., 12., 30., 50.], np.float32)\n z = np.logspace(-10., -1., 20).reshape((20, 1)).astype(np.float32)\n self.assertAllFinite(self.evaluate(tfp.math.log_bessel_ive(v, z)))\n\n @test_util.numpy_disable_gradient_test\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-3),\n (\"float64\", np.float64, 1e-4))\n def testLogBesselIveGradient(self, dtype, tol):\n v = tf.constant([-0.2, -1., 1., 0.5, 2.], dtype=dtype)[..., tf.newaxis]\n z = tf.constant([0.3, 0.5, 0.9, 1., 12., 22.], dtype=dtype)\n\n err = self.compute_max_gradient_error(\n functools.partial(tfp_math.log_bessel_ive, v), [z])\n self.assertLess(err, tol)\n\n @test_util.numpy_disable_gradient_test\n @parameterized.named_parameters((\"float32\", np.float32),\n (\"float64\", np.float64))\n def testJitGradBcastLogBesselIve(self, dtype):\n self.skip_if_no_xla()\n\n @tf.function(jit_compile=True)\n def f(v, z):\n dy = tf.random.normal(z.shape, seed=test_util.test_seed(), dtype=dtype)\n return tf.nest.map_structure(\n lambda t: () if t is None else t, # session.run doesn't like `None`.\n tfp.math.value_and_gradient(\n lambda v, z: tfp.math.log_bessel_ive(v, z)**2,\n (v, z),\n output_gradients=dy))\n\n v = tf.constant(0.5, dtype=dtype)\n z = tf.constant([[0.3, 0.5, 0.9], [1., 12., 22.]], dtype=dtype)\n\n self.evaluate(f(v, z))\n\n\n@test_util.test_all_tf_execution_regimes\nclass BesselKveTest(test_util.TestCase):\n\n def VerifyBesselKve(self, v, z, rtol):\n bessel_kve, v, z = self.evaluate([\n tfp.math.bessel_kve(v, z), v, z])\n scipy_kve = scipy_special.kve(v, z)\n self.assertAllClose(bessel_kve, scipy_kve, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32),\n (\"float64\", np.float64),\n )\n def testBesselKveAtZero(self, dtype):\n # Check that z = 0 returns inf for v = 0.\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform([10], 1., 10., seed=seed_stream(), dtype=dtype)\n z = tf.constant(0., dtype=dtype)\n self.assertAllClose(\n self.evaluate(tfp.math.bessel_kve(v, z)),\n np.full([10], np.inf, dtype=dtype))\n\n v = tf.constant([0.], dtype=dtype)\n self.assertAllClose(\n self.evaluate(tfp.math.bessel_kve(v, z)),\n np.full([1], np.inf, dtype=dtype))\n\n @parameterized.named_parameters(\n (\"float32\", np.float32),\n (\"float64\", np.float64),\n )\n def testBesselKveZNegativeNaN(self, dtype):\n # Check that z < 0 returns NaN for non-integer v.\n seed_stream = test_util.test_seed_stream()\n v = np.linspace(1.1, 10.2, num=11, dtype=dtype)\n z = tf.random.uniform([11], -10., -1., seed=seed_stream(), dtype=dtype)\n bessel_kve = self.evaluate(tfp.math.bessel_kve(v, z))\n self.assertTrue(np.all(np.isnan(bessel_kve)))\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveZNegativeVInteger(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = np.linspace(1., 10., num=10, dtype=dtype)\n z = tf.random.uniform([10], -10., -1., seed=seed_stream(), dtype=dtype)\n z, bessel_kve = self.evaluate([z, tfp.math.bessel_kve(v, z)])\n scipy_kve = scipy_special.kve(v, z)\n self.assertAllClose(bessel_kve, scipy_kve, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveZNegativeVLarge(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = np.linspace(100., 200., num=10, dtype=dtype)\n z = tf.random.uniform([10], -10., -1., seed=seed_stream(), dtype=dtype)\n z, bessel_kve = self.evaluate([z, tfp.math.bessel_kve(v, z)])\n scipy_kve = scipy_special.kve(v, z)\n self.assertAllClose(bessel_kve, scipy_kve, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1.5e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveVAndZSmall(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform([int(1e5)], seed=seed_stream(), dtype=dtype)\n self.VerifyBesselKve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 4e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveVAndZMedium(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselKve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 3e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveVAndZLarge(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 10., 50., seed=seed_stream(), dtype=dtype)\n v = tf.random.uniform([int(1e5)], 10., 50., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselKve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 7e-6),\n (\"float64\", np.float64, 7e-6),\n )\n def testBesselKveVLessThanZ(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n # Make v randomly less than z\n v = z * tf.random.uniform(\n [int(1e5)], 0.1, 0.5, seed=seed_stream(), dtype=dtype)\n self.VerifyBesselKve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 2e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveVGreaterThanZ(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform([int(1e5)], 1., 10., seed=seed_stream(), dtype=dtype)\n # Make z randomly less than v\n z = v * tf.random.uniform(\n [int(1e5)], 0.1, 0.5, seed=seed_stream(), dtype=dtype)\n self.VerifyBesselKve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 4e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveVNegative(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform(\n [int(1e5)], -10., -1., seed=seed_stream(), dtype=dtype)\n z = tf.random.uniform([int(1e5)], 1., 15., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselKve(v, z, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6),\n (\"float64\", np.float64, 1e-6),\n )\n def testBesselKveLargeZ(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform(\n [int(1e5)], minval=0., maxval=0.5, seed=seed_stream(), dtype=dtype)\n z = tf.random.uniform(\n [int(1e5)], minval=100., maxval=10000., seed=seed_stream(), dtype=dtype)\n self.VerifyBesselKve(v, z, rtol=rtol)\n\n @test_util.numpy_disable_gradient_test\n @parameterized.named_parameters(\n (\"float32\", np.float32),\n (\"float64\", np.float64),\n )\n def testBesselKveGradient(self, dtype):\n v = tf.constant([0.5, 1., 2., 5.])[..., tf.newaxis]\n z = tf.constant([10., 20., 30., 50., 12.,])\n\n err = self.compute_max_gradient_error(\n functools.partial(tfp_math.bessel_kve, v), [z])\n self.assertLess(err, 3e-4)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-6, 1e-5),\n (\"float64\", np.float64, 1e-6),\n )\n def testLogBesselKveCorrect(self, dtype, rtol, atol=1e-6):\n seed_stream = test_util.test_seed_stream()\n v = tf.random.uniform(\n [int(1e5)], minval=0.1, maxval=0.5, seed=seed_stream(), dtype=dtype)\n z = tf.random.uniform(\n [int(1e5)], minval=1., maxval=10., seed=seed_stream(), dtype=dtype)\n _, _, log_bessel_kve_expected_, log_bessel_kve_actual_ = self.evaluate([\n v,\n z,\n tf.math.log(tfp.math.bessel_kve(v, z)),\n tfp.math.log_bessel_kve(v, z)])\n self.assertAllClose(\n log_bessel_kve_expected_, log_bessel_kve_actual_, rtol=rtol, atol=atol)\n\n def testLogBesselTestNonInf(self):\n # Test that log_bessel_kve(v, z) has more resolution than simply computing\n # log(bessel_ive(v, z)). The inputs below will return inf in naive float64\n # computation.\n v = np.array([10., 12., 30., 50.], np.float32)\n z = np.logspace(-10., -1., 20).reshape((20, 1)).astype(np.float32)\n self.assertAllFinite(self.evaluate(tfp.math.log_bessel_kve(v, z)))\n\n @test_util.numpy_disable_gradient_test\n @parameterized.named_parameters(\n (\"float32\", np.float32, 1e-3),\n (\"float64\", np.float64, 1e-4))\n def testLogBesselKveGradient(self, dtype, tol):\n v = tf.constant([-0.2, -1., 1., 0.5, 2.], dtype=dtype)[..., tf.newaxis]\n z = tf.constant([0.3, 0.5, 0.9, 1., 12., 22.], dtype=dtype)\n\n err = self.compute_max_gradient_error(\n functools.partial(tfp_math.log_bessel_kve, v), [z])\n self.assertLess(err, tol)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2021 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Batch broadcasting meta-distribuion.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.bijectors import bijector as bijector_lib\nfrom tensorflow_probability.python.distributions import distribution as distribution_lib\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import parameter_properties\nfrom tensorflow_probability.python.internal import prefer_static as ps\nfrom tensorflow_probability.python.internal import tensor_util\nfrom tensorflow_probability.python.internal import tensorshape_util\n\n\n__all__ = ['BatchBroadcast']\n\n\ndef _make_bcast_fn(fn_name, n_event_shapes):\n \"\"\"Implements functions like mean, variance, etc.\"\"\"\n def fn(self, *args, **kwargs):\n val = getattr(self.distribution, fn_name)(*args, **kwargs)\n single_val_shape = self.batch_shape_tensor()\n if n_event_shapes:\n single_val_shape = ps.concat(\n [single_val_shape] + [self.event_shape_tensor()] * n_event_shapes,\n axis=0)\n return tf.broadcast_to(\n val, ps.broadcast_shape(ps.shape(val), single_val_shape))\n fn.__name__ = f'_{fn_name}'\n return fn\n\n\nclass BatchBroadcast(distribution_lib.Distribution):\n \"\"\"A distribution that broadcasts an underlying distribution's batch shape.\n\n This meta-distribution can be useful when we desire to implicitly broadcast\n an underlying distribution's batch shape with, or to, another shape, typically\n to parameterize a larger batch of distributions.\n\n This distribution supports two flavors of broadcasting. The\n `with_shape` argument broadcasts the underlying distribution's batch\n shape _with_ a compatible shape `with_shape`, obtaining a batch shape that\n results from the broadcast of these two shapes together. Alternatively,\n the `to_shape` argument broadcasts the underlying distribution's\n batch shape _to_ the exact shape specified. With an unnamed argument, the more\n permissive `with_shape` behavior is used.\n\n #### Examples\n\n ```python\n d = tfd.BatchBroadcast(tfd.Normal(tf.range(3.), 1.), with_shape=[2, 3])\n d.batch_shape # => [2, 3]\n d.distribution.batch_shape # => [3]\n d.event_shape # => []\n\n d = tfd.BatchBroadcast(tfd.Normal(tf.range(3.), 1.), to_shape=[2, 3])\n d.batch_shape # => [2, 3]\n\n df = tfd.Uniform(4., 5.).sample([10, 1])\n d = tfd.BatchBroadcast(\n tfd.WishartTriL(df=df, scale_tril=tf.eye(3)), with_shape=[2])\n d.batch_shape # => [10, 2]\n d.distribution.batch_shape # => [10, 1]\n d.event_shape # => [3, 3]\n\n d = tfd.BatchBroadcast(\n tfd.WishartTriL(df=df, scale_tril=tf.eye(3)), to_shape=[2])\n # => Exception: to_shape is too small\n\n d = tfd.BatchBroadcast(tfd.WishartTriL(df=df, scale_tril=tf.eye(3)),\n to_shape=[10, 2])\n d.batch_shape # => [10, 2]\n ```\n\n #### Example: Spatially distributed samples\n\n In some cases a particular batch shape may be required, but the underlying\n parameterization has a smaller representation.\n\n Suppose data is sampled in 10 different vicinities on a globe. We might write:\n\n ```python\n loc = tfp.random.spherical_uniform([10], 3)\n components_dist = tfd.VonMisesFisher(mean_direction=loc, concentration=50.)\n ```\n\n Now suppose we are operating 500 different experiments, each of which samples\n these different vicinities in different proportions. We might hope to write:\n\n ```python\n mixture_dist = tfd.Categorical(logits=tf.random.uniform([500, 10]))\n obs_dist = tfd.MixtureSameFamily(mixture_dist, components_dist)\n ```\n\n But this currently (Feb. 2021) causes an exception `ValueError:\n mixture_distribution.batch_shape ([500]) is not compatible with\n components_distribution.batch_shape ([])`.\n\n A naive fix would be to broadcast the parameters of `components_dist` to\n ensure the component distribution has batch shape `[500, 10]`. But this is\n wasteful in that it replicates a `[10, 3]`-shaped tensor 500 times, and will\n cause unnecessary computation, memory motion, etc. Using `BatchBroadcast` we\n may write:\n\n ```python\n obs_dist = tfd.MixtureSameFamily(\n mixture_dist, tfd.BatchBroadcast(components_dist, [500, 10]))\n ```\n\n This allows us to avoid avoid replicating any parameters, but achieve the\n requisite batch shape. If we would like to evaluate the likelihood of 20 given\n observation locations under each different experiment, we might write:\n\n ```python\n test_sites = tfp.random.spherical_uniform([20], 3)\n lp = tfd.Sample(obs_dist, 20).log_prob(test_sites) # shape [500]\n ```\n \"\"\"\n\n def __init__(self, distribution, with_shape=None, *, to_shape=None,\n validate_args=False, name=None):\n \"\"\"Constructs a new BatchBroadcast distribution.\n\n Args:\n distribution: The underlying distribution. Must have batch shape\n compatible with `broadcast_shape`.\n with_shape: The shape _with which_ the underlying distribution's batch\n shape is to be broadcast. The resulting batch shape may be different\n from either input. Mutually exclusive with `to_shape`.\n to_shape: The shape _to which_ the underlying distribution's batch\n shape is to be broadcast. This provides a stricter contract than\n `with_shape`, in that the resulting batch shape will be exactly the\n one provided in `to_shape`. Mutually exclusive with\n `with_shape`.\n validate_args: Indicates whether additional assertions should be used; may\n impose a performance penalty.\n name: Optional name for the distribution.\n \"\"\"\n parameters = dict(locals())\n self._distribution = distribution\n if (to_shape is None) == (with_shape is None):\n raise ValueError(\n 'Exactly one of `with_shape` or `to_shape` must be given.')\n self._with_shape = tensor_util.convert_nonref_to_tensor(\n with_shape, dtype_hint=tf.int32, as_shape_tensor=True,\n name='with_shape')\n self._to_shape = tensor_util.convert_nonref_to_tensor(\n to_shape, dtype_hint=tf.int32, as_shape_tensor=True,\n name='to_shape')\n with tf.name_scope(name or f'BatchBroadcast{distribution.name}') as name:\n super(BatchBroadcast, self).__init__(\n dtype=distribution.dtype,\n reparameterization_type=distribution.reparameterization_type,\n validate_args=validate_args,\n allow_nan_stats=distribution.allow_nan_stats,\n parameters=parameters,\n name=name)\n\n @classmethod\n def _parameter_properties(cls, dtype, num_classes=None):\n return dict(\n distribution=parameter_properties.BatchedComponentProperties(),\n to_shape=parameter_properties.ShapeParameterProperties(),\n with_shape=parameter_properties.ShapeParameterProperties())\n\n @property\n def distribution(self):\n return self._distribution\n\n @property\n def with_shape(self):\n return self._with_shape\n\n @property\n def to_shape(self):\n return self._to_shape\n\n @property\n def experimental_shard_axis_names(self):\n return self.distribution.experimental_shard_axis_names\n\n def __getitem__(self, slices):\n # Implementing this method would require logic similar to\n # slicing._slice_single_param, but mapped to distribution instances instead\n # of Tensors.\n raise NotImplementedError(\n 'Slices of `BatchBroadcast` are not implemented. Email '\n '[email protected] if this would be helpful.')\n\n def _batch_shape(self):\n if self.to_shape is None:\n return tf.broadcast_static_shape(\n self.distribution.batch_shape,\n tf.TensorShape(tf.get_static_value(self.with_shape)))\n return tf.TensorShape(tf.get_static_value(self.to_shape))\n\n def _batch_shape_tensor(self):\n if self.to_shape is None:\n return ps.broadcast_shape(self.distribution.batch_shape_tensor(),\n self.with_shape)\n return self.to_shape\n\n def _event_shape(self):\n return self.distribution.event_shape\n\n def _event_shape_tensor(self):\n return self.distribution.event_shape_tensor()\n\n def _sample_n(self, n, seed=None):\n batch_shape = self.batch_shape_tensor()\n batch_rank = ps.rank_from_shape(batch_shape)\n n_batch = ps.reduce_prod(batch_shape)\n\n underlying_batch_shape = self.distribution.batch_shape_tensor()\n underlying_batch_rank = ps.rank_from_shape(underlying_batch_shape)\n underlying_n_batch = ps.reduce_prod(underlying_batch_shape)\n\n # Left pad underlying shape with any necessary ones.\n underlying_bcast_shp = ps.concat(\n [ps.ones([ps.maximum(batch_rank - underlying_batch_rank, 0)],\n dtype=underlying_batch_shape.dtype),\n underlying_batch_shape],\n axis=0)\n\n # Determine how many underlying samples to produce.\n n_bcast_samples = ps.maximum(0, n_batch // underlying_n_batch)\n samps = self.distribution.sample([n, n_bcast_samples], seed=seed)\n\n is_dim_bcast = ps.not_equal(batch_shape, underlying_bcast_shp)\n\n event_shape = self.event_shape_tensor()\n event_rank = ps.rank_from_shape(event_shape)\n shp = ps.concat([[n], ps.where(is_dim_bcast, batch_shape, 1),\n underlying_bcast_shp,\n event_shape], axis=0)\n # Reshape to expand n_bcast_samples and ones-padded underlying_bcast_shp.\n samps = tf.reshape(samps, shp)\n # Interleave broadcast and underlying axis indices for transpose.\n interleaved_batch_axes = ps.reshape(\n ps.stack([ps.range(batch_rank),\n ps.range(batch_rank) + batch_rank],\n axis=-1),\n [-1]) + 1\n\n event_axes = ps.range(event_rank) + (1 + 2 * batch_rank)\n perm = ps.concat([[0], interleaved_batch_axes, event_axes], axis=0)\n samps = tf.transpose(samps, perm=perm)\n # Finally, reshape to the fully-broadcast batch shape.\n return tf.reshape(samps, ps.concat([[n], batch_shape, event_shape], axis=0))\n\n _log_prob = _make_bcast_fn('log_prob', n_event_shapes=0)\n _prob = _make_bcast_fn('prob', n_event_shapes=0)\n _log_cdf = _make_bcast_fn('log_cdf', n_event_shapes=0)\n _cdf = _make_bcast_fn('cdf', n_event_shapes=0)\n _log_survival_function = _make_bcast_fn(\n 'log_survival_function', n_event_shapes=0)\n _survival_function = _make_bcast_fn(\n 'survival_function', n_event_shapes=0)\n\n _entropy = _make_bcast_fn('entropy', n_event_shapes=0)\n _mode = _make_bcast_fn('mode', n_event_shapes=1)\n _mean = _make_bcast_fn('mean', n_event_shapes=1)\n _variance = _make_bcast_fn('variance', n_event_shapes=1)\n _stddev = _make_bcast_fn('stddev', n_event_shapes=1)\n _covariance = _make_bcast_fn('covariance', n_event_shapes=2)\n _quantile = _make_bcast_fn('quantile', n_event_shapes=1)\n\n def _default_event_space_bijector(self):\n bijector = self.distribution.experimental_default_event_space_bijector()\n if bijector is None:\n return None\n return _BroadcastingBijector(self, bijector)\n\n def _parameter_control_dependencies(self, is_init):\n if tensorshape_util.is_fully_defined(self.distribution.batch_shape):\n if self.to_shape is not None:\n static_to_shape = tf.get_static_value(self.to_shape)\n if static_to_shape is not None:\n bcast_shp = tf.broadcast_static_shape(\n tf.TensorShape(static_to_shape),\n self.distribution.batch_shape)\n if bcast_shp != static_to_shape:\n raise ValueError(f'Argument `to_shape` ({static_to_shape}) '\n 'is incompatible with underlying distribution '\n f'batch shape ({self.distribution.batch_shape}).')\n\n else:\n static_with_shape = tf.get_static_value(self.with_shape)\n if static_with_shape is not None:\n tf.broadcast_static_shape( # Ensure compatible.\n tf.TensorShape(static_with_shape),\n self.distribution.batch_shape)\n\n underlying = self.distribution._parameter_control_dependencies(is_init) # pylint: disable=protected-access\n if not self.validate_args:\n return underlying\n\n checks = []\n if self.to_shape is not None:\n if tensor_util.is_ref(self.to_shape) != is_init:\n checks += [assert_util.assert_equal(\n self.to_shape,\n ps.broadcast_shape(self.distribution.batch_shape_tensor(),\n self.to_shape),\n message='Argument `to_shape` is incompatible with underlying '\n 'distribution batch shape.')]\n else:\n if tensor_util.is_ref(self.with_shape) != is_init:\n checks += [tf.broadcast_dynamic_shape(\n self.distribution.batch_shape_tensor(),\n self.with_shape)]\n\n return tuple(checks) + tuple(underlying)\n\n def _sample_control_dependencies(self, value, **kwargs):\n return self.distribution._sample_control_dependencies(value, **kwargs) # pylint: disable=protected-access\n\n\nclass _BroadcastingBijector(bijector_lib.Bijector):\n \"\"\"Event space bijector for BatchBroadcast.\"\"\"\n\n def __init__(self, bcast_dist, bijector):\n parameters = dict(locals())\n self.bcast_dist = bcast_dist\n self.bijector = bijector\n super(_BroadcastingBijector, self).__init__(\n validate_args=bcast_dist.validate_args,\n dtype=bijector.dtype,\n forward_min_event_ndims=bijector.forward_min_event_ndims,\n inverse_min_event_ndims=bijector.inverse_min_event_ndims,\n parameters=parameters)\n\n def _single_event_shape(self):\n return tensorshape_util.concatenate(self.bcast_dist.batch_shape,\n self.bcast_dist.event_shape)\n\n def _single_event_shape_tensor(self):\n return ps.concat([self.bcast_dist.batch_shape_tensor(),\n self.bcast_dist.event_shape_tensor()], axis=0)\n\n def _forward_event_shape(self, x):\n return self.bijector.forward_event_shape(x)\n\n def _forward_event_shape_tensor(self, x):\n return self.bijector.forward_event_shape_tensor(x)\n\n def _inverse_event_shape(self, y):\n return self.bijector.inverse_event_shape(y)\n\n def _inverse_event_shape_tensor(self, y):\n return self.bijector.inverse_event_shape_tensor(y)\n\n def _bcast_x(self, x):\n shp = self.bijector.inverse_event_shape(self._single_event_shape())\n if not tensorshape_util.is_fully_defined(shp):\n shp = self.bijector.inverse_event_shape_tensor(\n self._single_event_shape_tensor())\n return tf.broadcast_to(x, ps.broadcast_shape(ps.shape(x), shp))\n\n def _forward(self, x):\n return self.bijector.forward(self._bcast_x(x))\n\n def _forward_log_det_jacobian(self, x):\n return self.bijector.forward_log_det_jacobian(self._bcast_x(x))\n\n def _bcast_y(self, y):\n return tf.broadcast_to(\n y, ps.broadcast_shape(ps.shape(y), self._single_event_shape_tensor()))\n\n def _inverse(self, y):\n return self.bijector.inverse(self._bcast_y(y))\n\n def _inverse_log_det_jacobian(self, y):\n return self.bijector.inverse_log_det_jacobian(self._bcast_y(y))\n", "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for Special Math Ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\n# Dependency imports\nimport numpy as np\nfrom scipy import special as sp_special\nfrom scipy import stats as sp_stats\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import special_math\nfrom tensorflow_probability.python.internal import test_util\nfrom tensorflow_probability.python.math.gradient import value_and_gradient\n\n\ndef _check_strictly_increasing(array_1d):\n diff = np.diff(array_1d)\n np.testing.assert_array_less(0, diff)\n\n\ndef _make_grid(dtype, grid_spec):\n \"\"\"Returns a uniform grid + noise, reshaped to shape argument.\"\"\"\n rng = np.random.RandomState(0)\n num_points = np.prod(grid_spec.shape)\n grid = np.linspace(grid_spec.min, grid_spec.max, num=num_points).astype(dtype)\n grid_spacing = (grid_spec.max - grid_spec.min) / num_points\n grid += 0.1 * grid_spacing * rng.randn(*grid.shape)\n # More useful if it's sorted (e.g. for testing monotonicity, or debugging).\n grid = np.sort(grid)\n return np.reshape(grid, grid_spec.shape)\n\n\nGridSpec = collections.namedtuple(\"GridSpec\", [\"min\", \"max\", \"shape\"])\n\nErrorSpec = collections.namedtuple(\"ErrorSpec\", [\"rtol\", \"atol\"])\n\n\n@test_util.test_all_tf_execution_regimes\nclass NdtrTest(test_util.TestCase):\n _use_log = False\n # Grid min/max chosen to ensure 0 < cdf(x) < 1.\n _grid32 = GridSpec(min=-12.9, max=5., shape=[100])\n _grid64 = GridSpec(min=-37.5, max=8., shape=[100])\n _error32 = ErrorSpec(rtol=1e-4, atol=0.)\n _error64 = ErrorSpec(rtol=1e-6, atol=0.)\n\n def _test_grid(self, dtype, grid_spec, error_spec):\n if self._use_log:\n self._test_grid_log(dtype, grid_spec, error_spec)\n else:\n self._test_grid_no_log(dtype, grid_spec, error_spec)\n\n def _test_grid_log(self, dtype, grid_spec, error_spec):\n\n grid = _make_grid(dtype, grid_spec)\n actual = self.evaluate(special_math.log_ndtr(grid))\n\n # Basic tests.\n # isfinite checks for NaN and Inf.\n self.assertTrue(np.isfinite(actual).all())\n # On the grid, -inf < log_cdf(x) < 0. In this case, we should be able\n # to use a huge grid because we have used tricks to escape numerical\n # difficulties.\n self.assertTrue((actual < 0).all())\n _check_strictly_increasing(actual)\n\n # Versus scipy.\n expected = sp_special.log_ndtr(grid)\n # Scipy prematurely goes to zero at some places that we don't. So don't\n # include these in the comparison.\n self.assertAllClose(\n expected.astype(np.float64)[expected < 0],\n actual.astype(np.float64)[expected < 0],\n rtol=error_spec.rtol,\n atol=error_spec.atol)\n\n def _test_grid_no_log(self, dtype, grid_spec, error_spec):\n\n grid = _make_grid(dtype, grid_spec)\n actual = self.evaluate(special_math.ndtr(grid))\n\n # Basic tests.\n # isfinite checks for NaN and Inf.\n self.assertTrue(np.isfinite(actual).all())\n # On the grid, 0 < cdf(x) < 1. The grid cannot contain everything due\n # to numerical limitations of cdf.\n self.assertTrue((actual > 0).all())\n self.assertTrue((actual < 1).all())\n _check_strictly_increasing(actual)\n\n # Versus scipy.\n expected = sp_special.ndtr(grid)\n # Scipy prematurely goes to zero at some places that we don't. So don't\n # include these in the comparison.\n self.assertAllClose(\n expected.astype(np.float64)[expected < 0],\n actual.astype(np.float64)[expected < 0],\n rtol=error_spec.rtol,\n atol=error_spec.atol)\n\n def test_float32(self):\n self._test_grid(np.float32, self._grid32, self._error32)\n\n def test_float64(self):\n self._test_grid(np.float64, self._grid64, self._error64)\n\n\n@test_util.test_all_tf_execution_regimes\nclass LogNdtrTestLower(NdtrTest):\n _use_log = True\n _grid32 = GridSpec(\n min=-100.,\n max=special_math.LOGNDTR_FLOAT32_LOWER, shape=[100])\n _grid64 = GridSpec(\n min=-100.,\n max=special_math.LOGNDTR_FLOAT64_LOWER, shape=[100])\n _error32 = ErrorSpec(rtol=1e-4, atol=0.)\n _error64 = ErrorSpec(rtol=1e-4, atol=0.)\n\n\n# The errors are quite large when the input is > 6 or so. Also,\n# scipy.sp_special.log_ndtr becomes zero very early, before 10,\n# (due to ndtr becoming 1). We approximate Log[1 + epsilon] as epsilon, and\n# avoid this issue.\n@test_util.test_all_tf_execution_regimes\nclass LogNdtrTestMid(NdtrTest):\n _use_log = True\n _grid32 = GridSpec(\n min=special_math.LOGNDTR_FLOAT32_LOWER,\n max=special_math.LOGNDTR_FLOAT32_UPPER, shape=[100])\n _grid64 = GridSpec(\n min=special_math.LOGNDTR_FLOAT64_LOWER,\n max=special_math.LOGNDTR_FLOAT64_UPPER, shape=[100])\n # Differences show up as soon as we're in the tail, so add some atol.\n _error32 = ErrorSpec(rtol=0.1, atol=1e-7)\n _error64 = ErrorSpec(rtol=0.1, atol=1e-7)\n\n\n@test_util.test_all_tf_execution_regimes\nclass LogNdtrTestUpper(NdtrTest):\n _use_log = True\n _grid32 = GridSpec(\n min=special_math.LOGNDTR_FLOAT32_UPPER,\n max=12., # Beyond this, log_cdf(x) may be zero.\n shape=[100])\n _grid64 = GridSpec(\n min=special_math.LOGNDTR_FLOAT64_UPPER,\n max=35., # Beyond this, log_cdf(x) may be zero.\n shape=[100])\n _error32 = ErrorSpec(rtol=1e-6, atol=1e-14)\n _error64 = ErrorSpec(rtol=1e-6, atol=1e-14)\n\n\n@test_util.test_all_tf_execution_regimes\nclass NdtrGradientTest(test_util.TestCase):\n _use_log = False\n _grid = GridSpec(min=-100., max=100., shape=[1, 2, 3, 8])\n _error32 = ErrorSpec(rtol=1e-4, atol=0)\n _error64 = ErrorSpec(rtol=1e-7, atol=0)\n\n def assert_all_true(self, v):\n self.assertAllEqual(np.ones_like(v, dtype=np.bool), v)\n\n def assert_all_false(self, v):\n self.assertAllEqual(np.zeros_like(v, dtype=np.bool), v)\n\n def _test_grad_finite(self, dtype):\n x = tf.constant([-100., 0., 100.], dtype=dtype)\n fn = special_math.log_ndtr if self._use_log else special_math.ndtr\n # Not having the lambda sanitzer means we'd get an `IndexError` whenever\n # the user supplied function has default args.\n output, grad_output = value_and_gradient(fn, x)\n # isfinite checks for NaN and Inf.\n output_, grad_output_ = self.evaluate([output, grad_output])\n self.assert_all_true(np.isfinite(output_))\n self.assert_all_true(np.isfinite(grad_output_[0]))\n\n def _test_grad_accuracy(self, dtype, grid_spec, error_spec):\n grid = _make_grid(dtype, grid_spec)\n _, actual_grad = self.evaluate(value_and_gradient(\n special_math.log_ndtr if self._use_log else special_math.ndtr, grid))\n\n # Check for NaN separately in order to get informative failures.\n self.assert_all_false(np.isnan(actual_grad))\n if self._use_log:\n g = np.reshape(actual_grad, [-1])\n half = np.ceil(len(g) / 2)\n self.assert_all_true(g[:int(half)] > 0.)\n self.assert_all_true(g[int(half):] >= 0.)\n else:\n # The ndtr gradient will only be non-zero in the range [-14, 14] for\n # float32 and [-38, 38] for float64.\n self.assert_all_true(actual_grad >= 0.)\n # isfinite checks for NaN and Inf.\n self.assert_all_true(np.isfinite(actual_grad))\n\n # Versus scipy.\n if not (sp_special and sp_stats):\n return\n\n expected_grad = sp_stats.norm.pdf(grid)\n if self._use_log:\n expected_grad /= sp_special.ndtr(grid)\n expected_grad[np.isnan(expected_grad)] = 0.\n # Scipy prematurely goes to zero at some places that we don't. So don't\n # include these in the comparison.\n self.assertAllClose(\n expected_grad.astype(np.float64)[expected_grad < 0],\n actual_grad.astype(np.float64)[expected_grad < 0],\n rtol=error_spec.rtol,\n atol=error_spec.atol)\n\n def test_float32(self):\n self._test_grad_accuracy(np.float32, self._grid, self._error32)\n self._test_grad_finite(np.float32)\n\n def test_float64(self):\n self._test_grad_accuracy(np.float64, self._grid, self._error64)\n self._test_grad_finite(np.float64)\n\n\n@test_util.test_all_tf_execution_regimes\nclass LogNdtrGradientTest(NdtrGradientTest):\n _use_log = True\n\n\n@test_util.test_all_tf_execution_regimes\nclass LogCDFLaplaceTest(test_util.TestCase):\n # Note that scipy.stats.laplace does not have a stable Log CDF, so we cannot\n # rely on scipy to cross check the extreme values.\n\n # Test will be done differently over different ranges. These are the values\n # such that when exceeded by x, produce output that causes the naive (scipy)\n # implementation to have numerical issues.\n #\n # If x = log(1 / (2 * eps)), then 0.5 * exp{-x} = eps.\n # With inserting eps = np.finfo(dtype).eps, we see that log(1 / (2 * eps)) is\n # the value of x such that any larger value will result in\n # 1 - 0.5 * exp{-x} = 0, which will cause the log_cdf_laplace code to take a\n # log # of zero. We therefore choose these as our cutoffs for testing.\n CUTOFF_FLOAT64_UPPER = np.log(1. / (2. * np.finfo(np.float64).eps)) - 1.\n CUTOFF_FLOAT32_UPPER = np.log(1. / (2. * np.finfo(np.float32).eps)) - 1.\n\n def assertAllTrue(self, x):\n self.assertAllEqual(np.ones_like(x, dtype=np.bool), x)\n\n def _test_grid_log(self, dtype, scipy_dtype, grid_spec, error_spec):\n grid = _make_grid(dtype, grid_spec)\n actual = self.evaluate(special_math.log_cdf_laplace(grid))\n\n # Basic tests.\n # isfinite checks for NaN and Inf.\n self.assertAllTrue(np.isfinite(actual))\n self.assertAllTrue((actual < 0))\n _check_strictly_increasing(actual)\n\n # Versus scipy.\n\n scipy_dist = sp_stats.laplace(loc=0., scale=1.)\n expected = scipy_dist.logcdf(grid.astype(scipy_dtype))\n self.assertAllClose(\n expected.astype(np.float64),\n actual.astype(np.float64),\n rtol=error_spec.rtol,\n atol=error_spec.atol)\n\n def test_float32_lower_and_mid_segment_scipy_float32_ok(self):\n # Choose values mild enough that we can use scipy in float32, which will\n # allow for a high accuracy match to scipy (since we both use float32).\n self._test_grid_log(\n np.float32, # dtype\n np.float32, # scipy_dtype\n GridSpec(min=-10, max=self.CUTOFF_FLOAT32_UPPER - 5, shape=[100]),\n ErrorSpec(rtol=5e-4, atol=0))\n\n def test_float32_all_segments_with_scipy_float64_ok(self):\n # Choose values outside the range where scipy float32 works.\n # Let scipy use float64. This means we\n # won't be exactly the same since we are in float32.\n self._test_grid_log(\n np.float32, # dtype\n np.float64, # scipy_dtype\n GridSpec(min=-50, max=self.CUTOFF_FLOAT32_UPPER + 5, shape=[100]),\n ErrorSpec(rtol=0.05, atol=0))\n\n def test_float32_extreme_values_result_and_gradient_finite_and_nonzero(self):\n # On the lower branch, log_cdf_laplace(x) = x, so we know this will be\n # fine, but test to -200 anyways.\n grid = _make_grid(\n np.float32, GridSpec(min=-200, max=80, shape=[20, 100]))\n grid = tf.convert_to_tensor(value=grid)\n\n actual, grad = value_and_gradient(special_math.log_cdf_laplace, grid)\n actual_, grad_ = self.evaluate([actual, grad])\n\n # isfinite checks for NaN and Inf.\n self.assertAllTrue(np.isfinite(actual_))\n self.assertAllTrue(np.isfinite(grad_))\n self.assertFalse(np.any(actual_ == 0))\n self.assertFalse(np.any(grad_ == 0))\n\n def test_float64_extreme_values_result_and_gradient_finite_and_nonzero(self):\n # On the lower branch, log_cdf_laplace(x) = x, so we know this will be\n # fine, but test to -200 anyways.\n grid = _make_grid(\n np.float64, GridSpec(min=-200, max=700, shape=[20, 100]))\n grid = tf.convert_to_tensor(value=grid)\n\n actual, grad = value_and_gradient(special_math.log_cdf_laplace, grid)\n actual_, grad_ = self.evaluate([actual, grad])\n\n # isfinite checks for NaN and Inf.\n self.assertAllTrue(np.isfinite(actual_))\n self.assertAllTrue(np.isfinite(grad_))\n self.assertFalse(np.any(actual_ == 0))\n self.assertFalse(np.any(grad_ == 0))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Probability 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# ============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nimport numpy as np\nfrom scipy import stats\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\n\nfrom tensorflow_probability.python.distributions import poisson as poisson_lib\nfrom tensorflow_probability.python.distributions.internal import statistical_testing as st\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import implementation_selection\nfrom tensorflow_probability.python.internal import test_util\ntfd = tfp.distributions\n\n\n@test_util.test_all_tf_execution_regimes\nclass PoissonTest(test_util.TestCase):\n\n def _make_poisson(self,\n rate,\n validate_args=True,\n force_probs_to_zero_outside_support=False):\n return tfd.Poisson(\n rate=rate,\n validate_args=validate_args,\n force_probs_to_zero_outside_support=force_probs_to_zero_outside_support)\n\n def testPoissonShape(self):\n lam = tf.constant([3.0] * 5)\n poisson = self._make_poisson(rate=lam)\n\n self.assertEqual(self.evaluate(poisson.batch_shape_tensor()), (5,))\n self.assertEqual(poisson.batch_shape, tf.TensorShape([5]))\n self.assertAllEqual(self.evaluate(poisson.event_shape_tensor()), [])\n self.assertEqual(poisson.event_shape, tf.TensorShape([]))\n\n def testInvalidLam(self):\n invalid_lams = [-.01, -1., -2.]\n for lam in invalid_lams:\n with self.assertRaisesOpError('Argument `rate` must be non-negative.'):\n poisson = self._make_poisson(rate=lam)\n self.evaluate(poisson.rate_parameter())\n\n def testZeroLam(self):\n lam = 0.\n poisson = tfd.Poisson(rate=lam, validate_args=True)\n self.assertAllClose(lam, self.evaluate(poisson.rate))\n self.assertAllClose(0., poisson.prob(3))\n self.assertAllClose(1., poisson.prob(0))\n self.assertAllClose(0., poisson.log_prob(0))\n\n def testPoissonLogPmfDiscreteMatchesScipy(self):\n batch_size = 12\n lam = tf.constant([3.0] * batch_size)\n lam_v = 3.0\n x = np.array([-3., -0.5, 0., 2., 2.2, 3., 3.1, 4., 5., 5.5, 6., 7.],\n dtype=np.float32)\n poisson = self._make_poisson(\n rate=lam, force_probs_to_zero_outside_support=True, validate_args=False)\n log_pmf = poisson.log_prob(x)\n self.assertEqual(log_pmf.shape, (batch_size,))\n self.assertAllClose(self.evaluate(log_pmf), stats.poisson.logpmf(x, lam_v))\n\n pmf = poisson.prob(x)\n self.assertEqual(pmf.shape, (batch_size,))\n self.assertAllClose(self.evaluate(pmf), stats.poisson.pmf(x, lam_v))\n\n def testPoissonLogPmfContinuousRelaxation(self):\n batch_size = 12\n lam = tf.constant([3.0] * batch_size)\n x = tf.constant([-3., -0.5, 0., 2., 2.2, 3., 3.1, 4., 5., 5.5, 6., 7.])\n poisson = self._make_poisson(\n rate=lam,\n force_probs_to_zero_outside_support=False,\n validate_args=False)\n\n expected_continuous_log_pmf = (\n x * poisson.log_rate_parameter()\n - tf.math.lgamma(1. + x) - poisson.rate_parameter())\n expected_continuous_log_pmf = tf.where(\n x >= 0., expected_continuous_log_pmf,\n dtype_util.as_numpy_dtype(\n expected_continuous_log_pmf.dtype)(-np.inf))\n expected_continuous_pmf = tf.exp(expected_continuous_log_pmf)\n\n log_pmf = poisson.log_prob(x)\n self.assertEqual((batch_size,), log_pmf.shape)\n self.assertAllClose(self.evaluate(log_pmf),\n self.evaluate(expected_continuous_log_pmf))\n\n pmf = poisson.prob(x)\n self.assertEqual((batch_size,), pmf.shape)\n self.assertAllClose(self.evaluate(pmf),\n self.evaluate(expected_continuous_pmf))\n\n @test_util.numpy_disable_gradient_test\n def testPoissonLogPmfGradient(self):\n batch_size = 6\n lam = tf.constant([3.0] * batch_size)\n lam_v = 3.0\n # Only non-negative values, as negative ones cause nans in the expected\n # value.\n x = np.array([0., 2., 3., 4., 5., 6.], dtype=np.float32)\n\n _, dlog_pmf_dlam = self.evaluate(tfp.math.value_and_gradient(\n lambda lam: self._make_poisson(rate=lam).log_prob(x), lam))\n\n # A finite difference approximation of the derivative.\n eps = 1e-6\n expected = (stats.poisson.logpmf(x, lam_v + eps)\n - stats.poisson.logpmf(x, lam_v - eps)) / (2 * eps)\n\n self.assertEqual(dlog_pmf_dlam.shape, (batch_size,))\n self.assertAllClose(dlog_pmf_dlam, expected)\n\n @test_util.numpy_disable_gradient_test\n def testPoissonLogPmfGradientAtZeroPmf(self):\n # Check that the derivative wrt parameter at the zero-prob points is zero.\n batch_size = 6\n lam = tf.constant([3.0] * batch_size)\n x = tf.constant([-2., -1., -0.5, 0.2, 1.5, 10.5])\n\n def poisson_log_prob(lam):\n return self._make_poisson(\n rate=lam,\n force_probs_to_zero_outside_support=True,\n validate_args=False).log_prob(x)\n _, dlog_pmf_dlam = self.evaluate(tfp.math.value_and_gradient(\n poisson_log_prob, lam))\n\n self.assertEqual(dlog_pmf_dlam.shape, (batch_size,))\n self.assertAllClose(dlog_pmf_dlam, np.zeros([batch_size]))\n\n def testPoissonLogPmfMultidimensional(self):\n batch_size = 6\n lam = tf.constant([[2.0, 4.0, 5.0]] * batch_size)\n lam_v = np.array([2.0, 4.0, 5.0], dtype=np.float32)\n x = np.array([[2., 3., 4., 5., 6., 7.]], dtype=np.float32).T\n\n poisson = self._make_poisson(rate=lam)\n log_pmf = poisson.log_prob(x)\n self.assertEqual(log_pmf.shape, (6, 3))\n self.assertAllClose(self.evaluate(log_pmf), stats.poisson.logpmf(x, lam_v))\n\n pmf = poisson.prob(x)\n self.assertEqual(pmf.shape, (6, 3))\n self.assertAllClose(self.evaluate(pmf), stats.poisson.pmf(x, lam_v))\n\n @test_util.jax_disable_test_missing_functionality(\n '`tf.math.igammac` is unimplemented in JAX backend.')\n def testPoissonCdf(self):\n batch_size = 12\n lam = tf.constant([3.0] * batch_size)\n lam_v = 3.0\n x = np.array([-3., -0.5, 0., 2., 2.2, 3., 3.1, 4., 5., 5.5, 6., 7.],\n dtype=np.float32)\n\n poisson = self._make_poisson(\n rate=lam, force_probs_to_zero_outside_support=True, validate_args=False)\n log_cdf = poisson.log_cdf(x)\n self.assertEqual(log_cdf.shape, (batch_size,))\n self.assertAllClose(self.evaluate(log_cdf), stats.poisson.logcdf(x, lam_v))\n\n cdf = poisson.cdf(x)\n self.assertEqual(cdf.shape, (batch_size,))\n self.assertAllClose(self.evaluate(cdf), stats.poisson.cdf(x, lam_v))\n\n def testPoissonSurvivalFunction(self):\n batch_size = 12\n lam = tf.constant([3.0] * batch_size)\n lam_v = 3.0\n x = np.array([-3., -0.5, 0., 2., 2.2, 3., 3.1, 4., 5., 5.5, 6., 7.],\n dtype=np.float32)\n\n poisson = self._make_poisson(\n rate=lam, force_probs_to_zero_outside_support=True, validate_args=False)\n log_survival = poisson.log_survival_function(x)\n self.assertEqual(log_survival.shape, (batch_size,))\n self.assertAllClose(\n self.evaluate(log_survival), stats.poisson.logsf(x, lam_v))\n\n survival = poisson.survival_function(x)\n self.assertEqual(survival.shape, (batch_size,))\n self.assertAllClose(self.evaluate(survival), stats.poisson.sf(x, lam_v))\n\n small_probs = tfd.Poisson(rate=0.123).log_survival_function(\n np.linspace(10, 19, 10))\n self.assertAllFinite(self.evaluate(small_probs))\n\n @test_util.jax_disable_test_missing_functionality(\n '`tf.math.igammac` is unimplemented in JAX backend.')\n def testPoissonCdfContinuousRelaxation(self):\n batch_size = 12\n lam = tf.constant([3.0] * batch_size)\n x = np.array([-3., -0.5, 0., 2., 2.2, 3., 3.1, 4., 5., 5.5, 6., 7.],\n dtype=np.float32)\n\n expected_continuous_cdf = tf.math.igammac(1. + x, lam)\n expected_continuous_cdf = tf.where(x >= 0., expected_continuous_cdf,\n tf.zeros_like(expected_continuous_cdf))\n expected_continuous_log_cdf = tf.math.log(expected_continuous_cdf)\n\n poisson = self._make_poisson(\n rate=lam,\n force_probs_to_zero_outside_support=False, validate_args=False)\n log_cdf = poisson.log_cdf(x)\n self.assertEqual(log_cdf.shape, (batch_size,))\n self.assertAllClose(self.evaluate(log_cdf),\n self.evaluate(expected_continuous_log_cdf))\n\n cdf = poisson.cdf(x)\n self.assertEqual(cdf.shape, (batch_size,))\n self.assertAllClose(self.evaluate(cdf),\n self.evaluate(expected_continuous_cdf))\n\n @test_util.jax_disable_test_missing_functionality(\n '`tf.math.igammac` is unimplemented in JAX backend.')\n @test_util.numpy_disable_gradient_test\n def testPoissonCdfGradient(self):\n batch_size = 12\n lam = tf.constant([3.0] * batch_size)\n lam_v = 3.0\n x = np.array([-3., -0.5, 0., 2., 2.2, 3., 3.1, 4., 5., 5.5, 6., 7.],\n dtype=np.float32)\n\n def cdf(lam):\n return self._make_poisson(\n rate=lam,\n force_probs_to_zero_outside_support=True,\n validate_args=False).cdf(x)\n _, dcdf_dlam = self.evaluate(tfp.math.value_and_gradient(cdf, lam))\n\n # A finite difference approximation of the derivative.\n eps = 1e-6\n expected = (stats.poisson.cdf(x, lam_v + eps)\n - stats.poisson.cdf(x, lam_v - eps)) / (2 * eps)\n\n self.assertEqual(dcdf_dlam.shape, (batch_size,))\n self.assertAllClose(dcdf_dlam, expected)\n\n @test_util.jax_disable_test_missing_functionality(\n '`tf.math.igammac` is unimplemented in JAX backend.')\n def testPoissonCdfMultidimensional(self):\n batch_size = 6\n lam = tf.constant([[2.0, 4.0, 5.0]] * batch_size)\n lam_v = np.array([2.0, 4.0, 5.0], dtype=np.float32)\n x = np.array([[2., 3., 4., 5., 6., 7.]], dtype=np.float32).T\n\n poisson = self._make_poisson(\n rate=lam, force_probs_to_zero_outside_support=True)\n log_cdf = poisson.log_cdf(x)\n self.assertEqual(log_cdf.shape, (6, 3))\n self.assertAllClose(self.evaluate(log_cdf), stats.poisson.logcdf(x, lam_v))\n\n cdf = poisson.cdf(x)\n self.assertEqual(cdf.shape, (6, 3))\n self.assertAllClose(self.evaluate(cdf), stats.poisson.cdf(x, lam_v))\n\n def testPoissonMean(self):\n lam_v = np.array([1.0, 3.0, 2.5], dtype=np.float32)\n poisson = self._make_poisson(rate=lam_v)\n self.assertEqual(poisson.mean().shape, (3,))\n self.assertAllClose(\n self.evaluate(poisson.mean()), stats.poisson.mean(lam_v))\n self.assertAllClose(self.evaluate(poisson.mean()), lam_v)\n\n def testPoissonVariance(self):\n lam_v = np.array([1.0, 3.0, 2.5], dtype=np.float32)\n poisson = self._make_poisson(rate=lam_v)\n self.assertEqual(poisson.variance().shape, (3,))\n self.assertAllClose(\n self.evaluate(poisson.variance()), stats.poisson.var(lam_v))\n self.assertAllClose(self.evaluate(poisson.variance()), lam_v)\n\n def testPoissonStd(self):\n lam_v = np.array([1.0, 3.0, 2.5], dtype=np.float32)\n poisson = self._make_poisson(rate=lam_v)\n self.assertEqual(poisson.stddev().shape, (3,))\n self.assertAllClose(\n self.evaluate(poisson.stddev()), stats.poisson.std(lam_v))\n self.assertAllClose(self.evaluate(poisson.stddev()), np.sqrt(lam_v))\n\n def testPoissonMode(self):\n lam_v = np.array([1.0, 3.0, 2.5, 3.2, 1.1, 0.05], dtype=np.float32)\n poisson = self._make_poisson(rate=lam_v)\n self.assertEqual(poisson.mode().shape, (6,))\n self.assertAllClose(self.evaluate(poisson.mode()), np.floor(lam_v))\n\n def testPoissonMultipleMode(self):\n lam_v = np.array([1.0, 3.0, 2.0, 4.0, 5.0, 10.0], dtype=np.float32)\n poisson = self._make_poisson(rate=lam_v)\n # For the case where lam is an integer, the modes are: lam and lam - 1.\n # In this case, we get back the larger of the two modes.\n self.assertEqual((6,), poisson.mode().shape)\n self.assertAllClose(lam_v, self.evaluate(poisson.mode()))\n\n def testPoissonSample(self):\n lam_v = 4.0\n lam = tf.constant(lam_v)\n # Choosing `n >= (k/rtol)**2, roughly ensures our sample mean should be\n # within `k` std. deviations of actual up to rtol precision.\n n = int(100e3)\n poisson = self._make_poisson(rate=lam)\n samples = poisson.sample(n, seed=test_util.test_seed())\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n,))\n self.assertEqual(sample_values.shape, (n,))\n self.assertAllClose(\n sample_values.mean(), stats.poisson.mean(lam_v), rtol=.01)\n self.assertAllClose(sample_values.var(), stats.poisson.var(lam_v),\n rtol=.013)\n\n def testAssertValidSample(self):\n lam_v = np.array([1.0, 3.0, 2.5], dtype=np.float32)\n poisson = self._make_poisson(rate=lam_v)\n with self.assertRaisesOpError('Condition x >= 0'):\n self.evaluate(poisson.cdf([-1.2, 3., 4.2]))\n\n def testPoissonSampleMultidimensionalMean(self):\n lam_v = np.array([np.arange(1, 51, dtype=np.float32)]) # 1 x 50\n poisson = self._make_poisson(rate=lam_v)\n # Choosing `n >= (k/rtol)**2, roughly ensures our sample mean should be\n # within `k` std. deviations of actual up to rtol precision.\n n = int(100e3)\n samples = poisson.sample(n, seed=test_util.test_seed())\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n, 1, 50))\n self.assertEqual(sample_values.shape, (n, 1, 50))\n self.assertAllClose(\n sample_values.mean(axis=0), stats.poisson.mean(lam_v), rtol=.01, atol=0)\n\n def testPoissonSampleMultidimensionalVariance(self):\n lam_v = np.array([np.arange(5, 15, dtype=np.float32)]) # 1 x 10\n poisson = self._make_poisson(rate=lam_v)\n # Choosing `n >= 2 * lam * (k/rtol)**2, roughly ensures our sample\n # variance should be within `k` std. deviations of actual up to rtol\n # precision.\n n = int(300e3)\n samples = poisson.sample(n, seed=test_util.test_seed())\n sample_values = self.evaluate(samples)\n self.assertEqual(samples.shape, (n, 1, 10))\n self.assertEqual(sample_values.shape, (n, 1, 10))\n\n self.assertAllClose(\n sample_values.var(axis=0), stats.poisson.var(lam_v), rtol=.03, atol=0)\n\n @test_util.tf_tape_safety_test\n def testGradientThroughRate(self):\n rate = tf.Variable(3.)\n dist = self._make_poisson(rate=rate)\n with tf.GradientTape() as tape:\n loss = -dist.log_prob([1., 2., 4.])\n grad = tape.gradient(loss, dist.trainable_variables)\n self.assertLen(grad, 1)\n self.assertAllNotNone(grad)\n\n def testAssertsNonNegativeRate(self):\n rate = tf.Variable([1., 2., -3.])\n self.evaluate(rate.initializer)\n with self.assertRaisesOpError('Argument `rate` must be non-negative.'):\n dist = self._make_poisson(rate=rate, validate_args=True)\n self.evaluate(dist.sample(seed=test_util.test_seed()))\n\n def testAssertsNonNegativeRateAfterMutation(self):\n rate = tf.Variable([1., 2., 3.])\n self.evaluate(rate.initializer)\n dist = self._make_poisson(rate=rate, validate_args=True)\n self.evaluate(dist.mean())\n with self.assertRaisesOpError('Argument `rate` must be non-negative.'):\n with tf.control_dependencies([rate.assign([1., 2., -3.])]):\n self.evaluate(dist.sample(seed=test_util.test_seed()))\n\n\n@test_util.test_all_tf_execution_regimes\nclass PoissonLogRateTest(PoissonTest):\n\n def _make_poisson(self,\n rate,\n validate_args=True,\n force_probs_to_zero_outside_support=False):\n return tfd.Poisson(\n log_rate=tf.math.log(rate),\n validate_args=validate_args,\n force_probs_to_zero_outside_support=force_probs_to_zero_outside_support)\n\n # No need to worry about the non-negativity of `rate` when using the\n # `log_rate` parameterization.\n def testInvalidLam(self):\n pass\n\n def testAssertsNonNegativeRate(self):\n pass\n\n def testAssertsNonNegativeRateAfterMutation(self):\n pass\n\n # The gradient is not tracked through tf.math.log(rate) in _make_poisson(),\n # so log_rate needs to be defined as a Variable and passed directly.\n @test_util.tf_tape_safety_test\n def testGradientThroughRate(self):\n log_rate = tf.Variable(3.)\n dist = tfd.Poisson(log_rate=log_rate, validate_args=True)\n with tf.GradientTape() as tape:\n loss = -dist.log_prob([1., 2., 4.])\n grad = tape.gradient(loss, dist.trainable_variables)\n self.assertLen(grad, 1)\n self.assertAllNotNone(grad)\n\n\n@test_util.test_graph_and_eager_modes\nclass PoissonSamplingTest(test_util.TestCase):\n\n @test_util.jax_disable_test_missing_functionality('tf stateless_poisson')\n def testSampleCPU(self):\n with tf.device('CPU'):\n _, runtime = self.evaluate(\n poisson_lib.random_poisson(\n shape=tf.constant([], dtype=tf.int32),\n rates=tf.constant(10.),\n seed=test_util.test_seed()))\n self.assertEqual(implementation_selection._RUNTIME_CPU, runtime)\n\n def testSampleGPU(self):\n if not tf.test.is_gpu_available():\n self.skipTest('no GPU')\n with tf.device('GPU'):\n _, runtime = self.evaluate(poisson_lib.random_poisson(\n shape=tf.constant([], dtype=tf.int32),\n rates=tf.constant(10.),\n seed=test_util.test_seed()))\n self.assertEqual(implementation_selection._RUNTIME_DEFAULT, runtime)\n\n def testSampleXLA(self):\n self.skip_if_no_xla()\n if not tf.executing_eagerly(): return # jit_compile is eager-only.\n log_rates = np.random.rand(4, 3).astype(np.float32)\n dist = tfd.Poisson(log_rate=log_rates, validate_args=True)\n # Verify the compile succeeds going all the way through the distribution.\n self.evaluate(\n tf.function(lambda: dist.sample(5, seed=test_util.test_seed()),\n jit_compile=True)())\n # Also test the low-level sampler and verify the XLA-friendly variant.\n _, runtime = self.evaluate(\n tf.function(poisson_lib.random_poisson, jit_compile=True)(\n shape=tf.constant([], dtype=tf.int32),\n rates=tf.constant(10.),\n seed=test_util.test_seed()))\n self.assertEqual(implementation_selection._RUNTIME_DEFAULT, runtime)\n\n def testSamplePoissonLowRates(self):\n # Low log rate (< log(10.)) samples would use Knuth's algorithm.\n rate = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5]\n log_rate = np.log(rate)\n num_samples = int(1e5)\n self.assertLess(\n self.evaluate(\n st.min_num_samples_for_dkwm_cdf_test(\n discrepancy=0.04, false_fail_rate=1e-9, false_pass_rate=1e-9)),\n num_samples)\n\n samples = poisson_lib._random_poisson_noncpu(\n shape=[num_samples],\n log_rates=log_rate,\n output_dtype=tf.float64,\n seed=test_util.test_seed())\n\n poisson = tfd.Poisson(log_rate=log_rate, validate_args=True)\n self.evaluate(\n st.assert_true_cdf_equal_by_dkwm(\n samples,\n poisson.cdf,\n st.left_continuous_cdf_discrete_distribution(poisson),\n false_fail_rate=1e-9))\n\n self.assertAllClose(\n self.evaluate(tf.math.reduce_mean(samples, axis=0)),\n stats.poisson.mean(rate),\n rtol=0.01)\n self.assertAllClose(\n self.evaluate(tf.math.reduce_variance(samples, axis=0)),\n stats.poisson.var(rate),\n rtol=0.05)\n\n def testSamplePoissonHighRates(self):\n # High rate (>= log(10.)) samples would use rejection sampling.\n rate = [10., 10.5, 11., 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5]\n log_rate = np.log(rate)\n num_samples = int(1e5)\n self.assertLess(\n self.evaluate(\n st.min_num_samples_for_dkwm_cdf_test(\n discrepancy=0.04, false_fail_rate=1e-9, false_pass_rate=1e-9)),\n num_samples)\n\n samples = poisson_lib._random_poisson_noncpu(\n shape=[num_samples],\n log_rates=log_rate,\n output_dtype=tf.float64,\n seed=test_util.test_seed())\n\n poisson = tfd.Poisson(log_rate=log_rate, validate_args=True)\n self.evaluate(\n st.assert_true_cdf_equal_by_dkwm(\n samples,\n poisson.cdf,\n st.left_continuous_cdf_discrete_distribution(poisson),\n false_fail_rate=1e-9))\n\n self.assertAllClose(\n self.evaluate(tf.math.reduce_mean(samples, axis=0)),\n stats.poisson.mean(rate),\n rtol=0.01)\n self.assertAllClose(\n self.evaluate(tf.math.reduce_variance(samples, axis=0)),\n stats.poisson.var(rate),\n rtol=0.05)\n\n def testSamplePoissonLowAndHighRates(self):\n rate = [1., 3., 5., 6., 7., 10., 13.0, 14., 15., 18.]\n log_rate = np.log(rate)\n num_samples = int(1e5)\n poisson = tfd.Poisson(log_rate=log_rate, validate_args=True)\n self.assertLess(\n self.evaluate(\n st.min_num_samples_for_dkwm_cdf_test(\n discrepancy=0.04, false_fail_rate=1e-9, false_pass_rate=1e-9)),\n num_samples)\n\n samples = poisson_lib._random_poisson_noncpu(\n shape=[num_samples],\n log_rates=log_rate,\n output_dtype=tf.float64,\n seed=test_util.test_seed())\n\n self.evaluate(\n st.assert_true_cdf_equal_by_dkwm(\n samples,\n poisson.cdf,\n st.left_continuous_cdf_discrete_distribution(poisson),\n false_fail_rate=1e-9))\n\n def testSamplePoissonInvalidRates(self):\n rate = [np.nan, -1., 0., 5., 7., 10., 13.0, 14., 15., 18.]\n log_rate = np.log(rate)\n samples = self.evaluate(\n poisson_lib._random_poisson_noncpu(\n shape=[int(1e5)],\n log_rates=log_rate,\n output_dtype=tf.float64,\n seed=test_util.test_seed()))\n self.assertAllClose(\n self.evaluate(tf.math.reduce_mean(samples, axis=0)),\n stats.poisson.mean(rate),\n rtol=0.01)\n self.assertAllClose(\n self.evaluate(tf.math.reduce_variance(samples, axis=0)),\n stats.poisson.var(rate),\n rtol=0.05)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2019 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"The PERT distribution.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.bijectors import chain as chain_bijector\nfrom tensorflow_probability.python.bijectors import scale as scale_bijector\nfrom tensorflow_probability.python.bijectors import shift as shift_bijector\nfrom tensorflow_probability.python.bijectors import sigmoid as sigmoid_bijector\nfrom tensorflow_probability.python.bijectors import softplus as softplus_bijector\nfrom tensorflow_probability.python.distributions import beta\nfrom tensorflow_probability.python.distributions import distribution\nfrom tensorflow_probability.python.distributions import transformed_distribution\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import parameter_properties\nfrom tensorflow_probability.python.internal import prefer_static as ps\nfrom tensorflow_probability.python.internal import reparameterization\nfrom tensorflow_probability.python.internal import tensor_util\n\n__all__ = [\n 'PERT',\n]\n\n\nclass PERT(distribution.Distribution):\n \"\"\"Modified PERT distribution for modeling expert predictions.\n\n The PERT distribution is a loc-scale family of Beta distributions\n fit onto a real interval between `low` and `high` values set by the user,\n along with a `peak` to indicate the expert's most frequent prediction.\n [1](https://en.wikipedia.org/wiki/PERT_distribution), and `temperature` to\n control how sharp the peak is.\n\n The distribution is similar to a [Triangular distribution]\n (https://en.wikipedia.org/wiki/Triangular_distribution)\n (i.e. `tfd.Triangular`) but with a smooth peak.\n\n #### Mathematical Details\n\n In terms of a Beta distribution, PERT can be expressed as\n\n ```none\n PERT ~ loc + scale * Beta(concentration1, concentration0)\n ```\n where\n\n ```none\n loc = low\n scale = high - low\n peak - low\n concentration1 = 1 + temperature * ------------\n high - low\n\n high - peak\n concentration0 = 1 + temperature * ------------\n high - low\n temperature > 0\n ```\n The support is `[low, high]`. The `peak` must fit in that interval:\n `low < peak < high`. The `temperature` is a positive parameter that\n controls the shape of the distribution. Higher values yield a sharper peak.\n\n The standard PERT distribution is obtained when `temperature = 4`.\n\n #### Examples\n ```python\n import tensorflow_probability as tfp\n tfd = tfp.distributions\n\n # Single PERT distribution\n dist = tfd.PERT(low=1., peak=7., high=11., temperature=4.)\n dist.sample(10)\n dist.prob(7.)\n dist.prob(0.) # Returns nan when the input is outside the support.\n\n # Multiple PERT distributions with varying temperature (broadcasted)\n dist = tfd.PERT(low=1., peak=7., high=11., temperature=[1., 2., 3., 4.])\n dist.sample(10)\n dist.prob(7.)\n dist.prob([[7.],[5.]])\n\n # Multiple PERT distributions with varying peak\n dist = tfd.PERT(low=1., peak=[2., 5., 8.], high=11., temperature=4.)\n dist.sample(10)\n dist.sample([10, 5])\n ```\n \"\"\"\n\n def __init__(self,\n low,\n peak,\n high,\n temperature=4.,\n validate_args=False,\n allow_nan_stats=False,\n name='PERT'):\n parameters = dict(locals())\n with tf.name_scope(name) as name:\n dtype = dtype_util.common_dtype([low, peak, high, temperature],\n tf.float32)\n self._low = tensor_util.convert_nonref_to_tensor(\n low, name='low', dtype=dtype)\n self._peak = tensor_util.convert_nonref_to_tensor(\n peak, name='peak', dtype=dtype)\n self._high = tensor_util.convert_nonref_to_tensor(\n high, name='high', dtype=dtype)\n self._temperature = tensor_util.convert_nonref_to_tensor(\n temperature, name='temperature', dtype=dtype)\n\n super(PERT, self).__init__(\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n reparameterization_type=reparameterization.FULLY_REPARAMETERIZED,\n parameters=parameters,\n dtype=dtype,\n name=name)\n\n def _transformed_beta(self, low=None, peak=None, high=None, temperature=None):\n low = tf.convert_to_tensor(self.low) if low is None else low\n peak = tf.convert_to_tensor(self.peak) if peak is None else peak\n high = tf.convert_to_tensor(self.high) if high is None else high\n temperature = (\n tf.convert_to_tensor(self.temperature)\n if temperature is None else temperature)\n scale = high - low\n concentration1 = (1. + temperature * (peak - low) / scale)\n concentration0 = (1. + temperature * (high - peak) / scale)\n return transformed_distribution.TransformedDistribution(\n distribution=beta.Beta(\n concentration1=concentration1,\n concentration0=concentration0,\n allow_nan_stats=self.allow_nan_stats),\n bijector=chain_bijector.Chain([\n shift_bijector.Shift(shift=low),\n # Broadcasting scale on affine bijector to match batch dimension.\n # This prevents dimension mismatch for operations like cdf.\n # Note that `concentration1` incorporates the broadcast of all four\n # parameters.\n scale_bijector.Scale(\n scale=tf.broadcast_to(\n scale, ps.shape(concentration1)))]))\n\n @classmethod\n def _parameter_properties(cls, dtype, num_classes=None):\n # pylint: disable=g-long-lambda\n return dict(\n low=parameter_properties.ParameterProperties(),\n # TODO(b/169874884): Support decoupled parameterization.\n high=parameter_properties.ParameterProperties(\n default_constraining_bijector_fn=parameter_properties\n .BIJECTOR_NOT_IMPLEMENTED,),\n # TODO(b/169874884): Support decoupled parameterization.\n peak=parameter_properties.ParameterProperties(\n default_constraining_bijector_fn=parameter_properties\n .BIJECTOR_NOT_IMPLEMENTED,),\n temperature=parameter_properties.ParameterProperties(\n default_constraining_bijector_fn=(\n lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype)))))\n # pylint: enable=g-long-lambda\n\n # Distribution properties\n @property\n def low(self):\n return self._low\n\n @property\n def peak(self):\n return self._peak\n\n @property\n def high(self):\n return self._high\n\n @property\n def temperature(self):\n return self._temperature\n\n def _event_shape(self):\n return ()\n\n def _sample_n(self, n, seed=None):\n return self._transformed_beta().sample(n, seed=seed)\n\n def _log_prob(self, x):\n return self._transformed_beta().log_prob(x)\n\n def _log_cdf(self, x):\n return self._transformed_beta().log_cdf(x)\n\n def _entropy(self):\n return self._transformed_beta().entropy()\n\n def _mean(self):\n return self._transformed_beta().mean()\n\n def _mode(self):\n return tf.convert_to_tensor(self.peak)\n\n def _variance(self):\n low = tf.convert_to_tensor(self.low)\n high = tf.convert_to_tensor(self.high)\n temperature = tf.convert_to_tensor(self.temperature)\n # We capture the tensors here to avoid multiple conversions.\n mean = self._transformed_beta(\n low=low, high=high, temperature=temperature).mean()\n return (mean - low) * (high - mean) / (temperature + 3.)\n\n def _quantile(self, value):\n return self._transformed_beta().quantile(value)\n\n def _default_event_space_bijector(self):\n return sigmoid_bijector.Sigmoid(\n low=self.low, high=self.high, validate_args=self.validate_args)\n\n def _parameter_control_dependencies(self, is_init):\n if not self.validate_args:\n return []\n assertions = []\n peak = None\n if is_init != tensor_util.is_ref(self.low):\n peak = tf.convert_to_tensor(self.peak)\n assertions.append(\n assert_util.assert_greater(\n peak, self.low, message='`peak` must be greater than `low`.'))\n if is_init != tensor_util.is_ref(self.high):\n peak = tf.convert_to_tensor(self.peak) if peak is None else peak\n assertions.append(\n assert_util.assert_greater(\n self.high, peak, message='`high` must be greater than `peak`.'))\n if is_init != tensor_util.is_ref(self.temperature):\n assertions.append(\n assert_util.assert_positive(\n self.temperature, message='`temperature` must be positive.'))\n return assertions\n\n def _sample_control_dependencies(self, x):\n assertions = []\n if not self.validate_args:\n return assertions\n assertions.append(assert_util.assert_greater_equal(\n x, self.low,\n message='Sample must be greater than or equal to `low`.'))\n assertions.append(assert_util.assert_less_equal(\n x, self.high,\n message='Sample must be less than or equal to `high`.'))\n return assertions\n", "# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for special.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\n\nfrom absl.testing import parameterized\nimport mpmath\nimport numpy as np\nfrom scipy import special as scipy_special\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import test_util\nfrom tensorflow_probability.python.math import hypergeometric as tfp_math\n\n\nclass Hyp2F1Test(test_util.TestCase):\n\n def _mpmath_hyp2f1(self, a, b, c, z):\n result = []\n for a_, b_, c_, z_ in zip(a, b, c, z):\n result.append(np.float64(mpmath.hyp2f1(a_, b_, c_, z_)))\n return np.array(result)\n\n def GenParam(self, low, high, dtype, seed):\n return tf.random.uniform(\n [int(1e4)], seed=seed,\n minval=low, maxval=high, dtype=dtype)\n\n def VerifyHyp2F1(\n self,\n dtype,\n rtol,\n a,\n b,\n c,\n z_lower=-0.9,\n z_upper=0.9,\n use_mpmath=False):\n comparison_hyp2f1 = self._mpmath_hyp2f1 if use_mpmath else scipy_special.hyp2f1\n seed_stream = test_util.test_seed_stream()\n z = tf.random.uniform(\n [int(1e4)], seed=seed_stream(),\n minval=z_lower, maxval=z_upper, dtype=dtype)\n\n hyp2f1, a, b, c, z = self.evaluate([\n tfp_math.hyp2f1_small_argument(a, b, c, z), a, b, c, z])\n expected = comparison_hyp2f1(a, b, c, z)\n self.assertAllClose(hyp2f1, expected, rtol=rtol)\n\n @parameterized.parameters(\n ([1], [1], [1], [1]),\n ([2], [3, 1], [5, 1, 1], [7, 1, 1, 1]),\n ([2, 1], [3], [5, 1, 1, 1], [7, 1, 1]),\n ([2, 1, 1, 1], [3, 1, 1], [5], [7, 1]),\n ([2, 1, 1], [3, 1, 1, 1], [5, 1], [7])\n )\n def testHyp2F1ShapeBroadcast(self, a_shape, b_shape, c_shape, z_shape):\n a = tf.zeros(a_shape, dtype=tf.float32)\n b = tf.zeros(b_shape, dtype=tf.float32)\n c = 10.5 * tf.ones(c_shape, dtype=tf.float32)\n z = tf.zeros(z_shape, dtype=tf.float32)\n broadcast_shape = functools.reduce(\n tf.broadcast_dynamic_shape, [a_shape, b_shape, c_shape, z_shape])\n hyp2f1 = tfp_math.hyp2f1_small_argument(a, b, c, z)\n broadcast_shape = self.evaluate(broadcast_shape)\n self.assertAllEqual(hyp2f1.shape, broadcast_shape)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 6e-3),\n (\"float64\", np.float64, 1e-6))\n def testHyp2F1AtOne(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(-10., 10., dtype, seed_stream())\n b = self.GenParam(-10., 10., dtype, seed_stream())\n # Ensure c > a + b so the evaluation is defined.\n c = a + b + 1.\n hyp2f1, a, b, c = self.evaluate([\n tfp_math.hyp2f1_small_argument(a, b, c, dtype(1.)), a, b, c])\n scipy_hyp2f1 = scipy_special.hyp2f1(a, b, c, dtype(1.))\n self.assertAllClose(hyp2f1, scipy_hyp2f1, rtol=rtol)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 6e-3),\n (\"float64\", np.float64, 1e-6))\n def testHyp2F1EqualParameters(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(-11.5, 11.5, dtype, seed_stream())\n b = self.GenParam(-11.5, 11.5, dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, a)\n self.VerifyHyp2F1(dtype, rtol, a, b, b)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 6e-3),\n (\"float64\", np.float64, 1e-6))\n def testHyp2F1ParamsSmallZSmallCLargerPositive(self, dtype, rtol):\n # Ensure that |c| > |b|.\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n b = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n c = self.GenParam(0.5, 1., dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 1e-6))\n def testHyp2F1ParamsSmallZSmallCLargerNegative(self, dtype, rtol):\n # Ensure that |c| > |b|.\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n b = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n c = self.GenParam(-1., -0.5, dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 4e-5))\n def testHyp2F1ParamsSmallZSmallCSmaller(self, dtype, rtol):\n # Ensure that |c| < |b|.\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(0.5, 1., dtype, seed_stream())\n b = self.GenParam(0.5, 1., dtype, seed_stream())\n c = self.GenParam(0., 0.5, dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 2e-4))\n def testHyp2F1ParamsSmallZPositiveLargeCLarger(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n b = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n c = self.GenParam(0.5, 1., dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c, z_lower=0.9, z_upper=1.)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 4e-6))\n def testHyp2F1ParamsSmallZPositiveLargeCSmaller(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(0.5, 1., dtype, seed_stream())\n b = self.GenParam(0.5, 1., dtype, seed_stream())\n c = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c, z_lower=0.9, z_upper=1.)\n\n @parameterized.named_parameters(\n (\"float32\", np.float32, 6e-3),\n (\"float64\", np.float64, 1e-6))\n def testHyp2F1ParamsSmallZNegativeLargeCLarger(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n b = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n c = self.GenParam(0.5, 1., dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c, z_lower=-1., z_upper=-0.9)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 1e-6))\n def testHyp2F1ParamsSmallZNegativeLargeCSmaller(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(0.5, 1., dtype, seed_stream())\n b = self.GenParam(0.5, 1., dtype, seed_stream())\n c = self.GenParam(-0.5, 0.5, dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c, z_lower=-1., z_upper=-0.9)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 2e-5))\n def testHyp2F1ParamsMediumCLarger(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(-10., 10., dtype, seed_stream())\n b = self.GenParam(-10., 10., dtype, seed_stream())\n c = self.GenParam(10., 20., dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c, z_lower=-1., z_upper=1.)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 1e-6))\n def testHyp2F1ParamsLargerCLarger(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(10., 50., dtype, seed_stream())\n b = self.GenParam(10., 50., dtype, seed_stream())\n c = self.GenParam(50., 100., dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c, z_lower=-1., z_upper=0.7)\n\n @parameterized.named_parameters(\n (\"float64\", np.float64, 6e-6))\n def testHyp2F1ParamsLargerCSmaller(self, dtype, rtol):\n seed_stream = test_util.test_seed_stream()\n a = self.GenParam(50., 80., dtype, seed_stream())\n b = self.GenParam(50., 80., dtype, seed_stream())\n c = self.GenParam(20., 50., dtype, seed_stream())\n self.VerifyHyp2F1(dtype, rtol, a, b, c, z_lower=-1., z_upper=1.)\n\n @test_util.numpy_disable_gradient_test\n @test_util.jax_disable_test_missing_functionality(\n \"Gradients not supported in JAX.\")\n def test2F1HypergeometricGradient(self):\n a = tf.constant([-0.1,], dtype=np.float64)[..., tf.newaxis]\n b = tf.constant([0.8,], dtype=np.float64)[..., tf.newaxis]\n c = tf.constant([9.9,], dtype=np.float64)[..., tf.newaxis]\n z = tf.constant([0.1], dtype=np.float64)\n err = self.compute_max_gradient_error(\n functools.partial(tfp_math.hyp2f1_small_argument, a, b, c), [z])\n self.assertLess(err, 2e-4)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Distributions for distributed computations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.distributions import distribution as distribution_lib\nfrom tensorflow_probability.python.distributions import log_prob_ratio\nfrom tensorflow_probability.python.internal import distribute_lib\nfrom tensorflow_probability.python.internal import parameter_properties\nfrom tensorflow_probability.python.internal import samplers\n\n\nJAX_MODE = False\n\n\ndef _implement_sharded_lp_fn(fn_name):\n \"\"\"Implements log_prob or unnormalized_log_prob.\"\"\"\n def lp_fn(self, x, reduce_over_shards=True, **kwargs):\n\n new_kwargs = dict(kwargs)\n if self.distribution.experimental_shard_axis_names:\n new_kwargs['reduce_over_shards'] = reduce_over_shards\n lp = getattr(self.distribution, fn_name)(x, **new_kwargs)\n if reduce_over_shards:\n lp = distribute_lib.psum(lp, self.experimental_shard_axis_names)\n\n return lp\n\n lp_fn.__name__ = f'_{fn_name}'\n return lp_fn\n\n\nclass Sharded(distribution_lib.Distribution):\n \"\"\"A meta-distribution meant for use in an SPMD distributed context.\n\n `Sharded` is a meta-distribution enables distributions to be used in SPMD\n programs. A `Sharded` distribution represents a random variable that has\n been split across a set of devices. The number of shards is the number of\n devices in the current TensorFlow DistributionStrategy or the provided JAX\n pmap axis.\n\n In practice, `Sharded` modifies its input distribution in two ways.\n First, when a `Sharded` distribution is sampled, it first folds the current\n device ID into the input random seed, resulting in different samples on each\n device. Second, when computing the `log_prob` of a value, a `Sharded`\n distribution aggregates the log-prob over all devices, resulting in the same\n synchronized value.\n \"\"\"\n\n def __init__(self, distribution, shard_axis_name=None, validate_args=False,\n name=None):\n\n \"\"\"Constructs a `Sharded` distribution.\n\n Args:\n distribution: The base distribution instance to transform. Typically an\n instance of `Distribution`.\n shard_axis_name: `str` or a list of strings for axis name(s). An empty\n list means that no sharding is actually done. This can be `None` under\n the TensorFlow backend (meaning a sharded axis is present, but\n anonymous). Only the JAX backend supports multiple axes names.\n validate_args: Python `bool`. Whether to validate input with asserts. If\n `validate_args` is `False`, and the inputs are invalid, correct behavior\n is not guaranteed.\n name: The name for ops managed by the distribution.\n Default value: `None` (i.e., `'Sharded' + distribution.name`).\n \"\"\"\n parameters = dict(locals())\n\n if shard_axis_name is None:\n if JAX_MODE:\n # In JAX, axes names matter and we don't know which axis name the user\n # might intend, so we bail.\n raise ValueError('Cannot provide a `None` axis name in JAX backend.')\n else:\n # In TF, there are no axes names, so we can pick a reasonable default.\n shard_axis_name = [True]\n\n # Use inner axes before outer axes\n full_shard_axis_name = (\n distribution.experimental_shard_axis_names +\n distribute_lib.canonicalize_axis_name(shard_axis_name))\n\n if not JAX_MODE:\n if len(full_shard_axis_name) > 1:\n raise ValueError(\n 'TensorFlow backend does not support multiple shard axes:\\n'\n 'inner shard_axis_names: '\n f'{list(distribution.experimental_shard_axis_names)}\\n'\n f'outer shard_axis_names: {list(shard_axis_name)}')\n\n if len(set(full_shard_axis_name)) != len(full_shard_axis_name):\n duplicates = set()\n seen = set()\n for axis_name in full_shard_axis_name:\n if axis_name in seen:\n duplicates.add(axis_name)\n seen.add(axis_name)\n raise ValueError(\n 'Found duplicate axis name(s).\\n'\n 'inner shard_axis_names: '\n f'{list(distribution.experimental_shard_axis_names)}\\n'\n f'outer shard_axis_names: {shard_axis_name}\\n'\n f'duplicates: {list(duplicates)}')\n\n with tf.name_scope(name or 'Sharded' + distribution.name) as name:\n self._distribution = distribution\n self._shard_axis_name = full_shard_axis_name\n super(Sharded, self).__init__(\n dtype=self._distribution.dtype,\n validate_args=validate_args,\n allow_nan_stats=self._distribution.allow_nan_stats,\n reparameterization_type=self._distribution.reparameterization_type,\n parameters=parameters,\n name=name)\n\n @property\n def experimental_shard_axis_names(self):\n return self._shard_axis_name\n\n @classmethod\n def _parameter_properties(cls, dtype, num_classes=None):\n return dict(\n distribution=parameter_properties.BatchedComponentProperties())\n\n @property\n def distribution(self):\n return self._distribution\n\n def _sample_n(self, n, seed, **kwargs):\n seed = samplers.sanitize_seed(seed, salt='sharded_sample')\n seed = distribute_lib.fold_in_axis_index(\n seed, self.experimental_shard_axis_names)\n return self.distribution.sample(sample_shape=n, seed=seed, **kwargs)\n\n _log_prob = _implement_sharded_lp_fn('log_prob')\n _unnormalized_log_prob = _implement_sharded_lp_fn('unnormalized_log_prob')\n\n def _batch_shape_tensor(self):\n return self.distribution.batch_shape_tensor()\n\n def _batch_shape(self):\n return self.distribution.batch_shape\n\n def _event_shape_tensor(self):\n return self.distribution.event_shape_tensor()\n\n def _event_shape(self):\n return self.distribution.event_shape\n\n def _parameter_control_dependencies(self, is_init):\n if JAX_MODE:\n return []\n return self.distribution._parameter_control_dependencies(is_init=is_init) # pylint: disable=protected-access\n\n def _default_event_space_bijector(self, *args, **kwargs):\n # TODO(b/175084455): This should likely be wrapped in a `tfb.Sharded`-like\n # construct.\n return self.distribution.experimental_default_event_space_bijector(\n *args, **kwargs)\n\n\n@log_prob_ratio.RegisterLogProbRatio(Sharded)\ndef _sharded_log_prob_ratio(p, x, q, y, name=None, reduce_over_shards=True):\n \"\"\"Distributed log-prob ratio for Sharded.\"\"\"\n with tf.name_scope(name or 'sharded_log_prob_ratio'):\n if p.experimental_shard_axis_names != q.experimental_shard_axis_names:\n raise ValueError(\n 'Mismatched axis names '\n f'\"{p.experimental_shard_axis_names}\" vs \"'\n f'\"{q.experimental_shard_axis_names}\"')\n\n def log_prob_ratio_fn(x, y):\n return log_prob_ratio.log_prob_ratio(p.distribution, x,\n q.distribution, y)\n\n if reduce_over_shards:\n axes = p.experimental_shard_axis_names\n\n return distribute_lib.make_psum_function(\n log_prob_ratio_fn, in_axes=(axes, axes), out_axes=axes,\n out_dtype=x)(x, y)\n return log_prob_ratio_fn(x, y)\n" ]
[ [ "scipy.stats.skellam.logpmf", "scipy.stats.skellam.mean", "tensorflow.compat.v2.Variable", "tensorflow.compat.v2.test.main", "tensorflow.compat.v2.constant", "numpy.linspace", "numpy.sqrt", "tensorflow.compat.v2.GradientTape", "scipy.stats.skellam.pmf", "tensorflow.compat.v2.math.log", "tensorflow.compat.v2.TensorShape", "numpy.array", "numpy.zeros", "scipy.stats.skellam.var", "scipy.stats.skellam.std" ], [ "numpy.log", "tensorflow.compat.v2.test.main", "numpy.sqrt", "numpy.std", "numpy.mean", "numpy.float32", "numpy.array", "numpy.exp", "numpy.random.RandomState" ], [ "tensorflow.compat.v2.convert_to_tensor" ], [ "tensorflow.compat.v2.nest.map_structure", "tensorflow.compat.v2.cast", "tensorflow.compat.v2.split", "tensorflow.compat.v2.nest.flatten" ], [ "numpy.arange", "numpy.array" ], [ "tensorflow.compat.v2.convert_to_tensor", "tensorflow.compat.v2.name_scope", "numpy.zeros" ], [ "tensorflow.compat.v2.math.xlogy", "tensorflow.compat.v2.name_scope", "tensorflow.compat.v2.math.log1p", "tensorflow.compat.v2.convert_to_tensor", "tensorflow.compat.v2.ones", "tensorflow.compat.v2.math.log", "tensorflow.compat.v2.math.xlog1py" ], [ "tensorflow.compat.v2.convert_to_tensor", "tensorflow.compat.v2.reduce_max", "tensorflow.compat.v2.reduce_sum", "tensorflow.compat.v2.while_loop", "tensorflow.compat.v2.TensorArray", "tensorflow.compat.v2.name_scope", "tensorflow.compat.v2.reshape", "tensorflow.compat.v2.zeros", "tensorflow.compat.v2.gather", "tensorflow.compat.v2.pad", "tensorflow.compat.v2.unstack", "tensorflow.compat.v2.reduce_prod", "tensorflow.compat.v2.control_dependencies", "tensorflow.compat.v2.matmul", "tensorflow.compat.v2.batch_to_space", "tensorflow.compat.v2.nn.depth_to_space", "tensorflow.compat.v2.get_static_value", "tensorflow.compat.v2.maximum", "tensorflow.compat.v2.concat", "tensorflow.compat.v2.cast", "tensorflow.compat.v2.compat.v1.enable_control_flow_v2" ], [ "numpy.array" ], [ "tensorflow.compat.v2.exp", "tensorflow.compat.v2.Variable", "numpy.log", "tensorflow.compat.v2.executing_eagerly", "tensorflow.compat.v2.test.main", "numpy.sqrt", "tensorflow.compat.v2.constant", "tensorflow.compat.v2.linalg.diag_part", "numpy.eye", "tensorflow.compat.v2.linalg.slogdet", "tensorflow.compat.v2.zeros", "tensorflow.compat.v2.eye", "numpy.array" ], [ "tensorflow.compat.v2.executing_eagerly", "tensorflow.compat.v2.test.main", "numpy.linspace", "numpy.sqrt", "tensorflow.compat.v2.enable_v2_behavior", "tensorflow.compat.v2.keras.layers.Dense", "tensorflow.compat.v2.reshape", "tensorflow.compat.v2.math.softmax", "numpy.zeros_like", "numpy.random.randn", "numpy.prod", "tensorflow.compat.v2.math.softplus", "tensorflow.compat.v2.constant", "tensorflow.compat.v2.TensorSpec" ], [ "tensorflow.compat.v2.function", "scipy.special.i1", "tensorflow.compat.v2.test.main", "tensorflow.compat.v2.constant", "scipy.special.ive", "numpy.linspace", "scipy.special.i0", "numpy.sqrt", "numpy.isnan", "numpy.logspace", "numpy.ones", "numpy.full", "scipy.special.kve", "numpy.array", "numpy.zeros" ], [ "tensorflow.compat.v2.get_static_value", "tensorflow.compat.v2.transpose", "tensorflow.compat.v2.name_scope", "tensorflow.compat.v2.reshape", "tensorflow.compat.v2.TensorShape" ], [ "scipy.stats.laplace", "numpy.linspace", "tensorflow.compat.v2.convert_to_tensor", "numpy.zeros_like", "numpy.any", "numpy.ones_like", "scipy.special.ndtr", "numpy.reshape", "numpy.finfo", "numpy.diff", "tensorflow.compat.v2.test.main", "numpy.isnan", "scipy.special.log_ndtr", "tensorflow.compat.v2.constant", "numpy.random.RandomState", "scipy.stats.norm.pdf", "numpy.isfinite", "numpy.sort", "numpy.testing.assert_array_less", "numpy.prod" ], [ "tensorflow.compat.v2.exp", "tensorflow.compat.v2.executing_eagerly", "numpy.sqrt", "numpy.linspace", "tensorflow.compat.v2.TensorShape", "scipy.stats.poisson.cdf", "tensorflow.compat.v2.math.reduce_mean", "numpy.arange", "tensorflow.compat.v2.math.reduce_variance", "tensorflow.compat.v2.math.lgamma", "scipy.stats.poisson.sf", "tensorflow.compat.v2.math.log", "scipy.stats.poisson.var", "scipy.stats.poisson.mean", "numpy.zeros", "tensorflow.compat.v2.Variable", "numpy.log", "tensorflow.compat.v2.function", "tensorflow.compat.v2.test.main", "scipy.stats.poisson.logpmf", "scipy.stats.poisson.logcdf", "tensorflow.compat.v2.math.igammac", "numpy.random.rand", "scipy.stats.poisson.std", "scipy.stats.poisson.pmf", "numpy.floor", "tensorflow.compat.v2.constant", "numpy.array", "tensorflow.compat.v2.test.is_gpu_available", "tensorflow.compat.v2.zeros_like", "tensorflow.compat.v2.GradientTape", "tensorflow.compat.v2.device", "scipy.stats.poisson.logsf" ], [ "tensorflow.compat.v2.convert_to_tensor", "tensorflow.compat.v2.name_scope" ], [ "tensorflow.compat.v2.test.main", "tensorflow.compat.v2.constant", "tensorflow.compat.v2.ones", "tensorflow.compat.v2.zeros", "numpy.array" ], [ "tensorflow.compat.v2.name_scope" ] ]
[ { "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": [], "tensorflow": [] } ]
Pandinosaurus/model-optimization
[ "12dc84dd34ee3c6eb08b381c0abcd65b31a42366", "12dc84dd34ee3c6eb08b381c0abcd65b31a42366" ]
[ "tensorflow_model_optimization/python/core/quantization/keras/collaborative_optimizations/cluster_preserve/cluster_preserve_quantize_registry.py", "tensorflow_model_optimization/python/core/clustering/keras/cluster_wrapper.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\"\"\"Registry responsible for built-in keras classes.\"\"\"\n\nimport logging\nimport tensorflow as tf\n\nfrom tensorflow_model_optimization.python.core.clustering.keras import clustering_registry\nfrom tensorflow_model_optimization.python.core.quantization.keras import quant_ops\nfrom tensorflow_model_optimization.python.core.quantization.keras import quantizers\nfrom tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_registry\nfrom tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantizers\n\nlayers = tf.keras.layers\nK = tf.keras.backend\n\nCLUSTER_CENTROIDS = 'cluster_centroids_tf'\nPULLING_INDICES = 'pulling_indices_tf'\nORIGINAL_WEIGHTS = 'ori_weights_vars_tf'\nWEIGHT_NAME = 'weight_name'\nCLUSTERING_IMPL = 'clst_impl'\nCENTROIDS_MASK = 'centroids_mask'\nSPARSITY_MASK = 'sparsity_mask'\n\n\ndef get_unique(t):\n \"\"\"Get unique values and lookup index from N-D tensor.\n\n Args:\n t: tensor\n Returns:\n unique value, lookup index (same shape as input tensor)\n Example:\n t:\n ([[1.0, 2.0],\n [2.0, 3.0],\n [3.0, 3.0],\n [1.0, 2.0]]\n )\n uniques:\n ([1.0, 2.0, 3.0])\n output final index:\n ([[0, 1],\n [1, 2],\n [2, 2],\n [0, 1]]\n )\n \"\"\"\n t_flatten = tf.reshape(t, shape=(-1,))\n uniques, index = tf.unique(t_flatten)\n return uniques, tf.reshape(index, shape=tf.shape(t))\n\n\nclass _ClusterPreserveInfo(object):\n \"\"\"ClusterPreserveInfo.\"\"\"\n\n def __init__(self, weight_attrs, quantize_config_attrs):\n \"\"\"ClusterPreserveInfo.\n\n Args:\n weight_attrs: list of cluster preservable weight attributes of layer.\n quantize_config_attrs: list of quantization configuration class name.\n \"\"\"\n self.weight_attrs = weight_attrs\n self.quantize_config_attrs = quantize_config_attrs\n\n\nclass ClusterPreserveQuantizeRegistry(object):\n \"\"\"ClusterPreserveQuantizeRegistry is for built-in keras layers.\"\"\"\n # The keys represent built-in keras layers; the first values represent the\n # the variables within the layers which hold the kernel weights, second\n # values represent the class name of quantization configuration for layers.\n # This decide the weights of layers with quantization configurations are\n # cluster preservable.\n _LAYERS_CONFIG_MAP = {\n layers.Conv2D:\n _ClusterPreserveInfo(['kernel'], ['Default8BitConvQuantizeConfig']),\n layers.Dense:\n _ClusterPreserveInfo(['kernel'], ['Default8BitQuantizeConfig']),\n\n # DepthwiseConv2D is supported with 8bit qat, but not with\n # clustering, thus for DepthwiseConv2D CQAT,\n # preserving clustered weights is disabled.\n layers.DepthwiseConv2D:\n _ClusterPreserveInfo(['depthwise_kernel'],\n ['Default8BitQuantizeConfig']),\n\n # layers that are supported with clustering, but not yet with qat\n # layers.Conv1D:\n # _ClusterPreserveInfo(['kernel'], []),\n # layers.Conv2DTranspose:\n # _ClusterPreserveInfo(['kernel'], []),\n # layers.Conv3D:\n # _ClusterPreserveInfo(['kernel'], []),\n # layers.Conv3DTranspose:\n # _ClusterPreserveInfo(['kernel'], []),\n # layers.LocallyConnected1D:\n # _ClusterPreserveInfo(['kernel'], ['Default8BitQuantizeConfig']),\n # layers.LocallyConnected2D:\n # _ClusterPreserveInfo(['kernel'], ['Default8BitQuantizeConfig']),\n\n # SeparableConv need verify from 8bit qat\n # layers.SeparableConv1D:\n # _ClusterPreserveInfo(['pointwise_kernel'],\n # ['Default8BitConvQuantizeConfig']),\n # layers.SeparableConv2D:\n # _ClusterPreserveInfo(['pointwise_kernel'],\n # ['Default8BitConvQuantizeConfig']),\n\n # Embedding need verify from 8bit qat\n # layers.Embedding: _ClusterPreserveInfo(['embeddings'], []),\n }\n\n _DISABLE_CLUSTER_PRESERVE = frozenset({\n layers.DepthwiseConv2D,\n })\n\n def __init__(self, preserve_sparsity):\n self._config_quantizer_map = {\n 'Default8BitQuantizeConfig':\n ClusterPreserveDefault8BitWeightsQuantizer(preserve_sparsity),\n 'Default8BitConvQuantizeConfig':\n ClusterPreserveDefault8BitConvWeightsQuantizer(preserve_sparsity),\n }\n\n @classmethod\n def _no_trainable_weights(cls, layer):\n \"\"\"Returns whether this layer has trainable weights.\n\n Args:\n layer: The layer to check for trainable weights.\n Returns:\n True/False whether the layer has trainable weights.\n \"\"\"\n return not layer.trainable_weights\n\n @classmethod\n def _disable_cluster_preserve(cls, layer):\n \"\"\"Returns whether to disable this layer for preserving clusters.\n\n Args:\n layer: The layer to check for disabling.\n Returns:\n True/False whether disabling this layer for preserving clusters.\n \"\"\"\n return layer.__class__ in cls._DISABLE_CLUSTER_PRESERVE\n\n @classmethod\n def supports(cls, layer):\n \"\"\"Returns whether the registry supports this layer type.\n\n Args:\n layer: The layer to check for support.\n Returns:\n True/False whether the layer type is supported.\n \"\"\"\n # layers without trainable weights are consider supported,\n # e.g., ReLU, Softmax, and AveragePooling2D.\n if cls._no_trainable_weights(layer):\n return True\n\n if layer.__class__ in cls._LAYERS_CONFIG_MAP:\n return True\n\n return False\n\n @classmethod\n def _weight_names(cls, layer):\n\n if cls._no_trainable_weights(layer):\n return []\n\n return cls._LAYERS_CONFIG_MAP[layer.__class__].weight_attrs\n\n def apply_cluster_preserve_quantize_config(self, layer, quantize_config):\n \"\"\"Applies cluster-preserve weight quantizer.\n\n Args:\n layer: The layer to check for support.\n quantize_config: quantization config for supporting cluster preservation\n on clustered weights\n Returns:\n The quantize_config with addon cluster preserve weight_quantizer.\n \"\"\"\n if not self.supports(layer):\n raise ValueError('Layer ' + str(layer.__class__) + ' is not supported.')\n\n # Example: ReLU, Softmax, and AveragePooling2D (without trainable weights)\n # DepthwiseConv2D (cluster_preserve is disabled)\n if self._no_trainable_weights(layer) or self._disable_cluster_preserve(\n layer):\n return quantize_config\n # Example: Conv2D, Dense layers\n if quantize_config.__class__.__name__ in self._LAYERS_CONFIG_MAP[\n layer.__class__].quantize_config_attrs:\n quantize_config.weight_quantizer = self._config_quantizer_map[\n quantize_config.__class__.__name__]\n else:\n raise ValueError('Configuration ' +\n str(quantize_config.__class__.__name__) +\n ' is not supported for Layer ' + str(layer.__class__) +\n '.')\n\n return quantize_config\n\n\nclass Default8bitClusterPreserveQuantizeRegistry(\n ClusterPreserveQuantizeRegistry):\n \"\"\"Default 8 bit ClusterPreserveQuantizeRegistry.\"\"\"\n\n def __init__(self, preserve_sparsity):\n super(Default8bitClusterPreserveQuantizeRegistry, self).__init__(\n preserve_sparsity)\n self.preserve_sparsity = preserve_sparsity\n\n def get_quantize_config(self, layer):\n \"\"\"Returns the quantization config with weight_quantizer for a given layer.\n\n Args:\n layer: input layer to return quantize config for.\n Returns:\n Returns the quantization config for cluster preserve weight_quantizer.\n \"\"\"\n quantize_config = (default_8bit_quantize_registry.\n Default8BitQuantizeRegistry().\n get_quantize_config(layer))\n cluster_aware_quantize_config = super(\n Default8bitClusterPreserveQuantizeRegistry,\n self).apply_cluster_preserve_quantize_config(layer, quantize_config)\n\n return cluster_aware_quantize_config\n\n\nclass ClusterPreserveDefaultWeightsQuantizer(quantizers.LastValueQuantizer):\n \"\"\"Quantize weights while preserving clusters.\"\"\"\n\n def __init__(\n self, num_bits, per_axis, symmetric, narrow_range, preserve_sparsity):\n \"\"\"ClusterPreserveDefaultWeightsQuantizer.\n\n Args:\n num_bits: Number of bits for quantization\n per_axis: Whether to apply per_axis quantization. The last dimension is\n used as the axis.\n symmetric: If true, use symmetric quantization limits instead of training\n the minimum and maximum of each quantization range separately.\n narrow_range: In case of 8 bits, narrow_range nudges the quantized range\n to be [-127, 127] instead of [-128, 127]. This ensures symmetric\n range has 0 as the centre.\n preserve_sparsity: Whether to apply prune-cluster-preserving quantization\n aware training.\n \"\"\"\n super(ClusterPreserveDefaultWeightsQuantizer, self).__init__(\n num_bits=num_bits,\n per_axis=per_axis,\n symmetric=symmetric,\n narrow_range=narrow_range,\n )\n self.preserve_sparsity = preserve_sparsity\n\n def _build_clusters(self, name, layer):\n \"\"\"Extracts the cluster centroids and cluster indices.\n\n Extracts cluster centroids and cluster indices from the pretrained\n clustered model when the input layer is clustered.\n\n Args:\n name: Name of weights in layer.\n layer: Quantization wrapped keras layer.\n Returns:\n A dictionary of the initial values of the\n cluster centroids, cluster indices, original weights,\n the pretrained flag for marking the first training\n epoch, and weight name.\n \"\"\"\n result = {}\n weights = getattr(layer.layer, name)\n if self.preserve_sparsity and not tf.reduce_any(weights == 0):\n self.preserve_sparsity = False\n logging.warning(\n 'Input layer does not contain zero weights, so apply CQAT instead.')\n centroids_mask = None\n centroids, lookup = get_unique(weights)\n num_centroids = tf.size(centroids)\n\n if self.preserve_sparsity:\n sparsity_mask = tf.math.divide_no_nan(weights, weights)\n zero_idx = tf.argmin(tf.abs(centroids), axis=-1)\n centroids_mask = 1.0 - tf.one_hot(zero_idx, num_centroids)\n result = {SPARSITY_MASK: sparsity_mask}\n\n # Prepare clustering variables for the Keras graph when clusters\n # exist, assuming we do not use number_of_clusters larger than 1024\n if num_centroids > 1024:\n return result\n else:\n clst_centroids_tf = layer.add_weight(\n CLUSTER_CENTROIDS,\n shape=centroids.shape,\n initializer=tf.keras.initializers.Constant(\n value=K.batch_get_value([centroids])[0]),\n dtype=centroids.dtype,\n trainable=True)\n\n ori_weights_tf = layer.add_weight(\n ORIGINAL_WEIGHTS,\n shape=weights.shape,\n initializer=tf.keras.initializers.Constant(\n value=K.batch_get_value([weights])[0]),\n dtype=weights.dtype,\n trainable=True)\n\n # Get clustering implementation according to layer type\n clustering_impl_cls = clustering_registry.ClusteringLookupRegistry(\n ).get_clustering_impl(layer.layer, name)\n clustering_impl = clustering_impl_cls(clst_centroids_tf)\n\n pulling_indices = tf.dtypes.cast(\n clustering_impl.get_pulling_indices(ori_weights_tf),\n lookup.dtype\n )\n\n pulling_indices_tf = layer.add_weight(\n PULLING_INDICES,\n shape=lookup.shape,\n initializer=tf.keras.initializers.Constant(\n value=K.batch_get_value([pulling_indices])[0]),\n dtype=lookup.dtype,\n trainable=False)\n\n result_clst = {\n CLUSTER_CENTROIDS: clst_centroids_tf,\n PULLING_INDICES: pulling_indices_tf,\n ORIGINAL_WEIGHTS: ori_weights_tf,\n WEIGHT_NAME: name,\n CLUSTERING_IMPL: clustering_impl,\n CENTROIDS_MASK: centroids_mask,\n }\n result.update(result_clst)\n return result\n\n def build(self, tensor_shape, name, layer):\n \"\"\"Build (P)CQAT wrapper.\n\n When preserve_sparsity is true and the input is clustered.\n\n Args:\n tensor_shape: Shape of weights which needs to be quantized.\n name: Name of weights in layer.\n layer: Quantization wrapped keras layer.\n Returns:\n Dictionary of centroids, indices and\n quantization params, the dictionary will be passed\n to __call__ function.\n \"\"\"\n # To get all the initial values from pretrained clustered model\n result = self._build_clusters(name, layer)\n # Result can have clustering nodes, then this is CQAT\n # Result can have both clustering nodes and sparsity mask, then\n # this will be PCQAT\n result.update(\n super(ClusterPreserveDefaultWeightsQuantizer,\n self).build(tensor_shape, name, layer))\n\n return result\n\n def __call__(self, inputs, training, weights, **kwargs):\n \"\"\"Apply cluster preserved quantization to the input tensor.\n\n Args:\n inputs: Input tensor (layer's weights) to be quantized.\n training: Whether the graph is currently training.\n weights: Dictionary of weights (params) the quantizer can use to\n quantize the tensor (layer's weights). This contains the weights\n created in the `build` function.\n **kwargs: Additional variables which may be passed to the quantizer.\n Returns:\n quantized tensor.\n \"\"\"\n if training:\n if CLUSTER_CENTROIDS in weights:\n if self.preserve_sparsity:\n weights[ORIGINAL_WEIGHTS].assign(\n tf.multiply(weights[ORIGINAL_WEIGHTS],\n weights[SPARSITY_MASK]))\n weights[CLUSTERING_IMPL].cluster_centroids.assign(\n weights[CLUSTERING_IMPL].\n cluster_centroids * weights[CENTROIDS_MASK]\n )\n weights[CLUSTER_CENTROIDS].assign(\n weights[CLUSTERING_IMPL].cluster_centroids\n )\n # Insert clustering variables\n weights[PULLING_INDICES].assign(tf.dtypes.cast(\n weights[CLUSTERING_IMPL].get_pulling_indices(\n weights[ORIGINAL_WEIGHTS]),\n weights[PULLING_INDICES].dtype\n ))\n\n output = weights[CLUSTERING_IMPL].get_clustered_weight(\n weights[PULLING_INDICES], weights[ORIGINAL_WEIGHTS])\n inputs.assign(output)\n else:\n if self.preserve_sparsity:\n inputs = tf.multiply(inputs, weights[SPARSITY_MASK])\n output = inputs\n else:\n output = inputs\n\n return quant_ops.LastValueQuantize(\n output,\n weights['min_var'],\n weights['max_var'],\n is_training=training,\n num_bits=self.num_bits,\n per_channel=self.per_axis,\n symmetric=self.symmetric,\n narrow_range=self.narrow_range\n )\n\n\nclass ClusterPreserveDefault8BitWeightsQuantizer(\n ClusterPreserveDefaultWeightsQuantizer):\n \"\"\"ClusterPreserveWeightsQuantizer for default 8bit weights.\"\"\"\n\n def __init__(self, preserve_sparsity):\n super(ClusterPreserveDefault8BitWeightsQuantizer,\n self).__init__(num_bits=8,\n per_axis=False,\n symmetric=True,\n narrow_range=True,\n preserve_sparsity=preserve_sparsity)\n self.preserve_sparsity = preserve_sparsity\n\n\nclass ClusterPreserveDefault8BitConvWeightsQuantizer(\n ClusterPreserveDefaultWeightsQuantizer,\n default_8bit_quantizers.Default8BitConvWeightsQuantizer):\n \"\"\"ClusterPreserveWeightsQuantizer for default 8bit Conv2D weights.\"\"\"\n\n def __init__(self, preserve_sparsity): # pylint: disable=super-init-not-called\n default_8bit_quantizers.Default8BitConvWeightsQuantizer.__init__(self)\n self.preserve_sparsity = preserve_sparsity\n\n def build(self, tensor_shape, name, layer):\n result = ClusterPreserveDefaultWeightsQuantizer._build_clusters(\n self, name, layer)\n result.update(\n default_8bit_quantizers.Default8BitConvWeightsQuantizer.build(\n self, tensor_shape, name, layer))\n return result\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Keras ClusterWeights wrapper API.\"\"\"\n\nimport operator\n\nimport tensorflow as tf\n\nfrom tensorflow_model_optimization.python.core.clustering.keras import cluster_config\nfrom tensorflow_model_optimization.python.core.clustering.keras import clusterable_layer\nfrom tensorflow_model_optimization.python.core.clustering.keras import clustering_centroids\nfrom tensorflow_model_optimization.python.core.clustering.keras import clustering_registry\n\nattrgetter = operator.attrgetter # pylint: disable=invalid-name\nkeras = tf.keras\nk = keras.backend\nLayer = keras.layers.Layer\nWrapper = keras.layers.Wrapper\nCentroidInitialization = cluster_config.CentroidInitialization\nGradientAggregation = cluster_config.GradientAggregation\n\n\nclass ClusterWeights(Wrapper):\n \"\"\"This wrapper augments a layer so the weight tensor(s) can be clustered.\n\n This wrapper implements nearest neighbor clustering algorithm. This algorithm\n ensures that only a specified number of unique values are used in a weight\n tensor. This allows for certain types of hardware to benefit from advanced\n weight compression techniques and the associated reduction in model memory\n footprint and bandwidth.\n\n From practical standpoint this is implemented using a lookup table to hold the\n cluster centroid values during model training. The weight array is populated\n with 'gather' operation so that during back propagation the gradients can be\n calculated in a normal way. The lookup table is then adjusted using the\n cumulative gradient values for the weights that correspond to the same\n centroid.\n\n The number of unique values required as well as the way cluster centroids\n are initialized are passed in the wrapper's constructor.\n\n The initial values of cluster centroids are fine-tuned during the training.\n \"\"\"\n\n def __init__(self,\n layer,\n number_of_clusters,\n cluster_centroids_init=CentroidInitialization.KMEANS_PLUS_PLUS,\n preserve_sparsity=False,\n cluster_per_channel=False,\n cluster_gradient_aggregation=GradientAggregation.SUM,\n **kwargs):\n if not isinstance(layer, Layer):\n raise ValueError(\n 'Please initialize `Cluster` layer with a '\n '`Layer` instance. You passed: {input}'.format(input=layer))\n\n if 'name' not in kwargs:\n kwargs['name'] = self._make_layer_name(layer)\n\n if isinstance(layer, clusterable_layer.ClusterableLayer):\n # A user-defined custom layer\n super(ClusterWeights, self).__init__(layer, **kwargs)\n elif clustering_registry.ClusteringRegistry.supports(layer):\n super(ClusterWeights, self).__init__(\n clustering_registry.ClusteringRegistry.make_clusterable(layer),\n **kwargs)\n else:\n raise ValueError(\n 'Please initialize `Cluster` with a supported layer. Layers should '\n 'either be a `ClusterableLayer` instance, or should be supported by '\n 'the ClusteringRegistry. You passed: {input}'.format(\n input=layer.__class__))\n\n if not isinstance(number_of_clusters, int):\n raise ValueError(\n 'number_of_clusters must be an integer. Given: {}'.format(\n number_of_clusters.__class__))\n\n limit_number_of_clusters = 2 if preserve_sparsity else 1\n if number_of_clusters <= limit_number_of_clusters:\n raise ValueError(\n 'number_of_clusters must be greater than {}. Given: {}'.format(\n limit_number_of_clusters, number_of_clusters))\n\n self._track_trackable(layer, name='layer')\n\n # The way how cluster centroids will be initialized\n self.cluster_centroids_init = cluster_centroids_init\n\n # The number of cluster centroids\n self.number_of_clusters = number_of_clusters\n\n # Whether to cluster Conv2D kernels per-channel.\n # In case the layer isn't a Conv2D, this isn't applicable\n self.cluster_per_channel = (\n cluster_per_channel if isinstance(layer, tf.keras.layers.Conv2D)\n else False)\n\n # Number of channels in a Conv2D layer, to be used the case of per-channel\n # clustering.\n self.num_channels = None\n\n # Whether to apply sparsity preservation or not\n self.preserve_sparsity = preserve_sparsity\n\n # The way to aggregate the gradient of each cluster centroid\n self.cluster_gradient_aggregation = cluster_gradient_aggregation\n\n # Stores the pairs of weight names and their respective sparsity masks\n self.sparsity_masks = {}\n\n # Stores the pairs of weight names and the zero centroids\n self.zero_idx = {}\n\n # Map weight names to original clusterable weights variables\n # Those weights will still be updated during backpropagation\n self.original_clusterable_weights = {}\n\n # Map the position of the original weight variable in the\n # child layer to the weight name\n self.position_original_weights = {}\n\n # Map weight names to corresponding clustering algorithms\n self.clustering_algorithms = {}\n\n # Map weight names to corresponding indices lookup tables\n self.pulling_indices = {}\n\n # Map weight names to corresponding cluster centroid variables\n self.cluster_centroids = {}\n\n # If the input shape was specified, then we need to preserve this\n # information in the layer. If this info is not preserved, then the `built`\n # state will not be preserved between serializations.\n if (not hasattr(self, '_batch_input_shape') and\n hasattr(layer, '_batch_input_shape')):\n self._batch_input_shape = self.layer._batch_input_shape\n\n # In the case of Conv2D layer, the data_format needs to be preserved to be\n # used for per-channel clustering\n if hasattr(layer, 'data_format'):\n self.data_format = self.layer.data_format\n else:\n self.data_format = None\n\n # Save the input shape specified in the build\n self.build_input_shape = None\n\n def _make_layer_name(self, layer):\n return '{}_{}'.format('cluster', layer.name)\n\n def _get_zero_idx_mask(self, centroids, zero_cluster):\n zero_idx_mask = (tf.cast(tf.math.not_equal(centroids,\n zero_cluster),\n dtype=tf.float32))\n return zero_idx_mask\n\n def _get_zero_centroid(self, centroids, zero_idx_mask):\n zero_centroid = tf.math.multiply(centroids,\n zero_idx_mask)\n return zero_centroid\n\n def get_weight_from_layer(self, weight_name):\n return getattr(self.layer, weight_name)\n\n def set_weight_to_layer(self, weight_name, new_weight):\n setattr(self.layer, weight_name, new_weight)\n\n def build(self, input_shape):\n super(ClusterWeights, self).build(input_shape)\n self.build_input_shape = input_shape\n\n # For every clusterable weights, create the clustering logic\n for weight_name, weight in self.layer.get_clusterable_weights():\n # Store the original weight in this wrapper\n # The child reference will be overridden in\n # update_clustered_weights_associations\n # The actual weight_name here for the clustering wrapper is not\n # necessarily the same as the original one from the layer wrapped.\n # For example for cells in StackedRNNCell, the names become\n # 'kernel/0', 'recurrent_kernel/0', 'kernel/1', 'recurrent_kernel/1'\n original_weight = self.get_weight_from_layer(weight_name)\n self.original_clusterable_weights[weight_name] = original_weight\n # Track the variable\n setattr(self, 'original_weight_' + weight_name,\n original_weight)\n # Store the position in layer.weights of original_weight to restore during\n # stripping\n position_original_weight = next(\n i for i, w in enumerate(self.layer.weights) if w is original_weight)\n self.position_original_weights[position_original_weight] = weight_name\n\n # In the case of per-channel clustering, the number of channels,\n # per-channel number of clusters, as well as the overall number\n # of clusters all need to be preserved in the wrapper.\n if self.cluster_per_channel:\n self.num_channels = (\n original_weight.shape[1] if self.data_format == 'channels_first'\n else original_weight.shape[-1])\n\n centroid_init_factory = clustering_centroids.CentroidsInitializerFactory\n centroid_init = centroid_init_factory.get_centroid_initializer(\n self.cluster_centroids_init)(weight, self.number_of_clusters,\n self.cluster_per_channel,\n self.num_channels,\n self.preserve_sparsity)\n\n # Init the cluster centroids\n cluster_centroids = (centroid_init.get_cluster_centroids())\n\n self.cluster_centroids[weight_name] = self.add_weight(\n '{}{}'.format('cluster_centroids_', weight_name),\n shape=(cluster_centroids.shape),\n dtype=weight.dtype,\n trainable=True,\n initializer=tf.keras.initializers.Constant(value=cluster_centroids))\n\n # Init the weight clustering algorithm\n if isinstance(self.layer, tf.keras.layers.RNN):\n if isinstance(self.layer.cell, tf.keras.layers.StackedRNNCells):\n weight_name_no_index = weight_name.split('/')[0]\n else:\n weight_name_no_index = weight_name\n elif isinstance(self.layer, tf.keras.layers.Bidirectional):\n weight_name_no_index = weight_name.split('/')[0]\n else:\n weight_name_no_index = weight_name\n self.clustering_algorithms[weight_name] = (\n clustering_registry.ClusteringLookupRegistry().get_clustering_impl(\n self.layer, weight_name_no_index, self.cluster_per_channel)\n (\n clusters_centroids=self.cluster_centroids[weight_name],\n cluster_gradient_aggregation=self.cluster_gradient_aggregation,\n data_format=self.data_format,\n ))\n\n # Init the pulling_indices (weights associations)\n pulling_indices = (\n self.clustering_algorithms[weight_name].get_pulling_indices(\n weight))\n self.pulling_indices[weight_name] = self.add_weight(\n '{}{}'.format('pulling_indices_', weight_name),\n shape=pulling_indices.shape,\n dtype=tf.int64,\n trainable=False,\n synchronization=tf.VariableSynchronization.ON_READ,\n aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA,\n initializer=tf.keras.initializers.Constant(value=pulling_indices))\n\n if self.preserve_sparsity:\n # Init the sparsity mask\n clustered_weights = (\n self.clustering_algorithms[weight_name].get_clustered_weight(\n pulling_indices, original_weight))\n self.sparsity_masks[weight_name] = (\n tf.cast(tf.math.not_equal(clustered_weights, 0), dtype=tf.float32))\n # If the model is pruned (which we suppose), this is approximately zero\n self.zero_idx[weight_name] = tf.argmin(\n tf.abs(self.cluster_centroids[weight_name]), axis=-1)\n\n def update_clustered_weights_associations(self):\n for weight_name, original_weight in self.original_clusterable_weights.items(\n ):\n\n if self.preserve_sparsity:\n # In the case of per-channel clustering, sparsity\n # needs to be preserved per-channel\n if self.cluster_per_channel:\n for channel in range(self.num_channels):\n zero_idx_mask = (\n self._get_zero_idx_mask(\n self.cluster_centroids[weight_name][channel],\n self.cluster_centroids[weight_name][channel][\n self.zero_idx[weight_name][channel]]))\n self.cluster_centroids[weight_name][channel].assign(\n self._get_zero_centroid(\n self.cluster_centroids[weight_name][channel],\n zero_idx_mask))\n else:\n # Set the smallest centroid to zero to force sparsity\n # and avoid extra cluster from forming\n zero_idx_mask = self._get_zero_idx_mask(\n self.cluster_centroids[weight_name],\n self.cluster_centroids[weight_name][self.zero_idx[weight_name]])\n self.cluster_centroids[weight_name].assign(\n self._get_zero_centroid(self.cluster_centroids[weight_name],\n zero_idx_mask))\n\n # During training, the original zero weights can drift slightly.\n # We want to prevent this by forcing them to stay zero at the places\n # where they were originally zero to begin with.\n original_weight = tf.math.multiply(original_weight,\n self.sparsity_masks[weight_name])\n\n # Update pulling indices (cluster associations)\n pulling_indices = (\n self.clustering_algorithms[weight_name].get_pulling_indices(\n original_weight))\n self.pulling_indices[weight_name].assign(pulling_indices)\n\n # Update clustered weights\n clustered_weights = (\n self.clustering_algorithms[weight_name].get_clustered_weight(\n pulling_indices, original_weight))\n\n # Replace the weights with their clustered counterparts\n # Remove weight_name index so the wrapper layer weight_name can match\n # the original one\n self.set_weight_to_layer(weight_name,\n clustered_weights)\n\n def call(self, inputs, training=None, **kwargs):\n # Update cluster associations in order to set the latest weights\n self.update_clustered_weights_associations()\n\n return self.layer.call(inputs, **kwargs)\n\n def compute_output_shape(self, input_shape):\n return self.layer.compute_output_shape(input_shape)\n\n def get_config(self):\n base_config = super(ClusterWeights, self).get_config()\n config = {\n 'number_of_clusters': self.number_of_clusters,\n 'cluster_centroids_init': self.cluster_centroids_init,\n 'preserve_sparsity': self.preserve_sparsity,\n 'cluster_gradient_aggregation': self.cluster_gradient_aggregation,\n 'cluster_per_channel': self.cluster_per_channel,\n **base_config\n }\n return config\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n config = config.copy()\n\n number_of_clusters = config.pop('number_of_clusters')\n cluster_centroids_init = config.pop('cluster_centroids_init')\n preserve_sparsity = config.pop('preserve_sparsity')\n cluster_gradient_aggregation = config.pop('cluster_gradient_aggregation')\n cluster_per_channel = config.pop('cluster_per_channel')\n\n config['number_of_clusters'] = number_of_clusters\n config['cluster_centroids_init'] = cluster_config.CentroidInitialization(\n cluster_centroids_init)\n config['preserve_sparsity'] = preserve_sparsity\n config['cluster_gradient_aggregation'] = cluster_gradient_aggregation\n config['cluster_per_channel'] = cluster_per_channel\n\n layer = tf.keras.layers.deserialize(\n config.pop('layer'), custom_objects=custom_objects)\n config['layer'] = layer\n\n return cls(**config)\n\n @property\n def trainable(self):\n return self.layer.trainable\n\n @trainable.setter\n def trainable(self, value):\n self.layer.trainable = value\n\n @property\n def trainable_weights(self):\n return self.layer.trainable_weights + self._trainable_weights\n\n @property\n def non_trainable_weights(self):\n return self.layer.non_trainable_weights + self._non_trainable_weights\n\n @property\n def updates(self):\n return self.layer.updates + self._updates\n\n @property\n def losses(self):\n return self.layer.losses + self._losses\n\n def get_weights(self):\n return self.layer.get_weights()\n\n def set_weights(self, weights):\n self.layer.set_weights(weights)\n\n\nclass ClusterWeightsRNN(ClusterWeights):\n \"\"\"This wrapper augments a RNN layer so that the weights can be clustered.\n\n The weight_name of a single cell in RNN layers is marked with an index in\n registry. In the wrapper layer, the index needs to be removed for matching\n the attribute of the cell layer.\n \"\"\"\n\n def get_weight_name_without_index(self, weight_name):\n weight_name_with_index = weight_name.split('/')\n return weight_name_with_index[0], int(weight_name_with_index[1])\n\n def get_return_layer_cell(self, index):\n return_layer_cell = (self.layer.forward_layer.cell if index == 0 else\n self.layer.backward_layer.cell)\n return return_layer_cell\n\n def get_weight_from_layer(self, weight_name):\n weight_name_no_index, i = self.get_weight_name_without_index(weight_name)\n if hasattr(self.layer, 'cell'):\n if isinstance(self.layer.cell, tf.keras.layers.StackedRNNCells):\n return getattr(self.layer.cell.cells[i], weight_name_no_index)\n else:\n return getattr(self.layer.cell, weight_name_no_index)\n elif isinstance(self.layer, tf.keras.layers.Bidirectional):\n if i < 0 or i > 1:\n raise ValueError(\n 'Unsupported number of cells in the layer to get weights from.')\n return_layer_cell = self.get_return_layer_cell(i)\n return getattr(return_layer_cell, weight_name_no_index)\n else:\n raise ValueError('No cells in the RNN layer to get weights from.')\n\n def set_weight_to_layer(self, weight_name, new_weight):\n weight_name_no_index, i = self.get_weight_name_without_index(weight_name)\n if hasattr(self.layer, 'cell'):\n if isinstance(self.layer.cell, tf.keras.layers.StackedRNNCells):\n return setattr(self.layer.cell.cells[i],\n weight_name_no_index,\n new_weight)\n else:\n return setattr(self.layer.cell, weight_name_no_index, new_weight)\n elif isinstance(self.layer, tf.keras.layers.Bidirectional):\n if i < 0 or i > 1:\n raise ValueError(\n 'Unsupported number of cells in the layer to set weights for.')\n return_layer_cell = self.get_return_layer_cell(i)\n return setattr(return_layer_cell, weight_name_no_index, new_weight)\n else:\n raise ValueError('No cells in the RNN layer to set weights for.')\n\n\nclass ClusterWeightsMHA(ClusterWeights):\n \"\"\"This wrapper augments a keras MHA layer so that the weights can be clustered.\"\"\"\n\n def get_weight_from_layer(self, weight_name):\n pre, _, post = weight_name.rpartition('.')\n return getattr(getattr(self.layer, pre), post)\n\n def set_weight_to_layer(self, weight_name, new_weight):\n pre, _, post = weight_name.rpartition('.')\n layer = attrgetter(pre)(self.layer)\n setattr(layer, post, new_weight)\n\n def strip_clustering(self):\n \"\"\"The restore from config is not working for MHA layer.\n\n Weights are not created when the build function is called. Therefore,\n original weights have been replaced in the layer.\n\n Returns:\n Updated layer.\n \"\"\"\n for weight_name, original_weight in (\n self.original_clusterable_weights.items()):\n\n # Get the clustered weights\n clustered_weight = self.get_weight_from_layer(weight_name)\n\n # Re-assign these weights to the original\n original_weight.assign(clustered_weight)\n setattr(self.layer, weight_name, original_weight)\n\n return self.layer\n\n" ]
[ [ "tensorflow.multiply", "tensorflow.unique", "tensorflow.shape", "tensorflow.reduce_any", "tensorflow.reshape", "tensorflow.one_hot", "tensorflow.math.divide_no_nan", "tensorflow.size", "tensorflow.abs" ], [ "tensorflow.math.multiply", "tensorflow.math.not_equal", "tensorflow.abs", "tensorflow.keras.initializers.Constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
Luciano233/OCR_Japanease
[ "055bdd0cc8e4d053dfb471cd642b1616ba0938d1" ]
[ "nets/classifiernet.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .block import Mish, SeparableConv2d, Block\n\nclass WideTipXception(nn.Module):\n def __init__(self, num_class):\n super(WideTipXception, self).__init__()\n\n self.conv1 = nn.Conv2d(1, 192, 3, 2, 1, bias=True)\n self.bn1 = nn.BatchNorm2d(192)\n self.mish = Mish()\n\n self.conv2 = nn.Conv2d(192, 512, 3, 1, 1, bias=True)\n self.bn2 = nn.BatchNorm2d(512)\n\n self.block1 = Block(512,1024,3,1)\n self.block2 = Block(1024,1024,3,1)\n self.block3 = Block(1024,1024,3,1)\n self.block4 = Block(1024,1024,3,1)\n self.block5 = Block(1024,1024,3,1)\n self.block6 = Block(1024,2048,2,2)\n self.block7 = Block(2048,3072,2,2)\n\n self.conv3 = SeparableConv2d(3072,4096,3,stride=1,padding=0,bias=True)\n self.fc = nn.Linear(4096, num_class)\n\n def forward(self, input):\n x = self.conv1(input)\n x = self.bn1(x)\n x = self.mish(x)\n\n x = self.conv2(x)\n x = self.bn2(x)\n\n x = self.block1(x)\n x = self.block2(x)\n x = self.block3(x)\n x = self.block4(x)\n x = self.block5(x)\n x = self.block6(x)\n x = self.block7(x)\n\n x = self.mish(x)\n x = self.conv3(x)\n\n x = self.mish(x)\n x = F.adaptive_avg_pool2d(x, (1, 1))\n x = x.view(x.size(0), -1)\n result = self.fc(x)\n\n return result\n\ndef get_classifiernet(num_class):\n model = WideTipXception(num_class)\n return model\n" ]
[ [ "torch.nn.Linear", "torch.nn.Conv2d", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.BatchNorm2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
HMS-CardiacMR/MyoMapNet-Myocardial-Parametric-Mapping
[ "1e2dee8d6d1f97722eba91618462537faf9efba7" ]
[ "InLine_Implementation/Code/utils/fftutils.py" ]
[ "\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport torch\n\n################################################################################\n################################################################################\n\ndef roll_nn(X, axis, n):\n f_idx = tuple(slice(None, None, None) if i != axis else slice(0, n, None) for i in range(X.dim()))\n b_idx = tuple(slice(None, None, None) if i != axis else slice(n, None, None) for i in range(X.dim()))\n front = X[f_idx]\n back = X[b_idx]\n return torch.cat([back, front], axis)\n\ndef fftshift2d(x, dims = [2, 3]):\n real, imag = torch.unbind(x, -1)\n for dim in dims:\n n_shift = real.size(dim)//2\n if real.size(dim) % 2 != 0:\n n_shift += 1 # for odd-sized images\n real = roll_nn(real, axis=dim, n=n_shift)\n imag = roll_nn(imag, axis=dim, n=n_shift)\n return torch.stack((real, imag), -1) # last dim=2 (real&imag)\n\ndef ifftshift2d(x, dims = [2, 3]):\n real, imag = torch.unbind(x, -1)\n for dim in dims[::-1]:\n real = roll_nn(real, axis=dim, n=real.size(dim)//2)\n imag = roll_nn(imag, axis=dim, n=imag.size(dim)//2)\n return torch.stack((real, imag), -1) # last dim=2 (real&imag)\n\n\n################################################################################\n################################################################################\n\n\ndef roll_n(X, axis, n):\n f_idx = tuple(slice(None, None, None) if i != axis else slice(0, n, None) for i in range(X.dim()))\n b_idx = tuple(slice(None, None, None) if i != axis else slice(n, None, None) for i in range(X.dim()))\n front = X[f_idx]\n back = X[b_idx]\n return torch.cat([back, front], axis)\n\ndef batch_fftshift2d(x, dims = [-2, -3]):\n real, imag = torch.unbind(x, -1)\n for dim in range(1, len(real.size())):\n n_shift = real.size(dim)//2\n if real.size(dim) % 2 != 0:\n n_shift += 1 # for odd-sized images\n real = roll_n(real, axis=dim, n=n_shift)\n imag = roll_n(imag, axis=dim, n=n_shift)\n return torch.stack((real, imag), -1) # last dim=2 (real&imag)\n\ndef batch_ifftshift2d(x):\n real, imag = torch.unbind(x, -1)\n for dim in range(len(real.size()) - 1, 0, -1):\n real = roll_n(real, axis=dim, n=real.size(dim)//2)\n imag = roll_n(imag, axis=dim, n=imag.size(dim)//2)\n return torch.stack((real, imag), -1) # last dim=2 (real&imag)\n\n\n\n\n\n################################################################################\n################################################################################\n\ndef prepare_grid(m, n):\n x = np.linspace(-(m // 2)/(m / 2), (m // 2)/(m / 2) - (1 - m % 2)*2/m, num=m)\n y = np.linspace(-(n // 2)/(n / 2), (n // 2)/(n / 2) - (1 - n % 2)*2/n, num=n)\n xv, yv = np.meshgrid(y, x)\n angle = np.arctan2(yv, xv)\n rad = np.sqrt(xv**2 + yv**2)\n rad[m//2][n//2] = rad[m//2][n//2 - 1]\n log_rad = np.log2(rad)\n return log_rad, angle\n\ndef rcosFn(width, position):\n N = 256 # abritrary\n X = np.pi * np.array(range(-N-1, 2))/2/N\n Y = np.cos(X)**2\n Y[0] = Y[1]\n Y[N+2] = Y[N+1]\n X = position + 2*width/np.pi*(X + np.pi/4)\n return X, Y\n\ndef pointOp(im, Y, X):\n out = np.interp(im.flatten(), X, Y)\n return np.reshape(out, im.shape)\n\ndef getlist(coeff):\n straight = [bands for scale in coeff[1:-1] for bands in scale]\n straight = [coeff[0]] + straight + [coeff[-1]]\n return straight\n\n################################################################################\n# NumPy reference implementation (fftshift and ifftshift)\n\n# def fftshift(x, axes=None):\n# \"\"\"\n# Shift the zero-frequency component to the center of the spectrum.\n# This function swaps half-spaces for all axes listed (defaults to all).\n# Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.\n# Parameters\n# \"\"\"\n# x = np.asarray(x)\n# if axes is None:\n# axes = tuple(range(x.ndim))\n# shift = [dim // 2 for dim in x.shape]\n# shift = [x.shape[ax] // 2 for ax in axes]\n# return np.roll(x, shift, axes)\n#\n# def ifftshift(x, axes=None):\n# \"\"\"\n# The inverse of `fftshift`. Although identical for even-length `x`, the\n# functions differ by one sample for odd-length `x`.\n# \"\"\"\n# x = np.asarray(x)\n# if axes is None:\n# axes = tuple(range(x.ndim))\n# shift = [-(dim // 2) for dim in x.shape]\n# shift = [-(x.shape[ax] // 2) for ax in axes]\n# return np.roll(x, shift, axes)" ]
[ [ "numpy.log2", "numpy.sqrt", "numpy.linspace", "torch.cat", "numpy.reshape", "numpy.cos", "numpy.arctan2", "torch.unbind", "torch.stack", "numpy.meshgrid" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
natemalek/molen-pater-nathan-rma-thesis-coreference-with-singletons
[ "3d2d6c751eadd6438a80b0c24f48b2635bc6acc7" ]
[ "deep-coref/modified_keras/examples/babi_memnn.py" ]
[ "from __future__ import print_function\nfrom keras.models import Sequential\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.core import Activation, Dense, Merge, Permute, Dropout\nfrom keras.layers.recurrent import LSTM\nfrom keras.datasets.data_utils import get_file\nfrom keras.preprocessing.sequence import pad_sequences\nfrom functools import reduce\nimport tarfile\nimport numpy as np\nimport re\n\n\"\"\"\nTrain a memory network on the bAbI dataset.\n\nReferences:\n- Jason Weston, Antoine Bordes, Sumit Chopra, Tomas Mikolov, Alexander M. Rush,\n \"Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks\",\n http://arxiv.org/abs/1503.08895\n\n- Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, Rob Fergus,\n \"End-To-End Memory Networks\",\n http://arxiv.org/abs/1503.08895\n\nReaches 93% accuracy on task 'single_supporting_fact_10k' after 70 epochs.\nTime per epoch: 3s on CPU (core i7).\n\"\"\"\n\n\ndef tokenize(sent):\n '''Return the tokens of a sentence including punctuation.\n\n >>> tokenize('Bob dropped the apple. Where is the apple?')\n ['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple', '?']\n '''\n return [x.strip() for x in re.split('(\\W+)?', sent) if x.strip()]\n\n\ndef parse_stories(lines, only_supporting=False):\n '''Parse stories provided in the bAbi tasks format\n\n If only_supporting is true, only the sentences that support the answer are kept.\n '''\n data = []\n story = []\n for line in lines:\n line = line.decode('utf-8').strip()\n nid, line = line.split(' ', 1)\n nid = int(nid)\n if nid == 1:\n story = []\n if '\\t' in line:\n q, a, supporting = line.split('\\t')\n q = tokenize(q)\n substory = None\n if only_supporting:\n # Only select the related substory\n supporting = map(int, supporting.split())\n substory = [story[i - 1] for i in supporting]\n else:\n # Provide all the substories\n substory = [x for x in story if x]\n data.append((substory, q, a))\n story.append('')\n else:\n sent = tokenize(line)\n story.append(sent)\n return data\n\n\ndef get_stories(f, only_supporting=False, max_length=None):\n '''Given a file name, read the file, retrieve the stories, and then convert the sentences into a single story.\n\n If max_length is supplied, any stories longer than max_length tokens will be discarded.\n '''\n data = parse_stories(f.readlines(), only_supporting=only_supporting)\n flatten = lambda data: reduce(lambda x, y: x + y, data)\n data = [(flatten(story), q, answer) for story, q, answer in data if not max_length or len(flatten(story)) < max_length]\n return data\n\n\ndef vectorize_stories(data, word_idx, story_maxlen, query_maxlen):\n X = []\n Xq = []\n Y = []\n for story, query, answer in data:\n x = [word_idx[w] for w in story]\n xq = [word_idx[w] for w in query]\n y = np.zeros(len(word_idx) + 1) # let's not forget that index 0 is reserved\n y[word_idx[answer]] = 1\n X.append(x)\n Xq.append(xq)\n Y.append(y)\n return (pad_sequences(X, maxlen=story_maxlen),\n pad_sequences(Xq, maxlen=query_maxlen), np.array(Y))\n\n\npath = get_file('babi-tasks-v1-2.tar.gz',\n origin='http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz')\ntar = tarfile.open(path)\n\nchallenges = {\n # QA1 with 10,000 samples\n 'single_supporting_fact_10k': 'tasks_1-20_v1-2/en-10k/qa1_single-supporting-fact_{}.txt',\n # QA2 with 10,000 samples\n 'two_supporting_facts_10k': 'tasks_1-20_v1-2/en-10k/qa2_two-supporting-facts_{}.txt',\n}\nchallenge_type = 'single_supporting_fact_10k'\nchallenge = challenges[challenge_type]\n\nprint('Extracting stories for the challenge:', challenge_type)\ntrain_stories = get_stories(tar.extractfile(challenge.format('train')))\ntest_stories = get_stories(tar.extractfile(challenge.format('test')))\n\nvocab = sorted(reduce(lambda x, y: x | y, (set(story + q + [answer]) for story, q, answer in train_stories + test_stories)))\n# Reserve 0 for masking via pad_sequences\nvocab_size = len(vocab) + 1\nstory_maxlen = max(map(len, (x for x, _, _ in train_stories + test_stories)))\nquery_maxlen = max(map(len, (x for _, x, _ in train_stories + test_stories)))\n\nprint('-')\nprint('Vocab size:', vocab_size, 'unique words')\nprint('Story max length:', story_maxlen, 'words')\nprint('Query max length:', query_maxlen, 'words')\nprint('Number of training stories:', len(train_stories))\nprint('Number of test stories:', len(test_stories))\nprint('-')\nprint('Here\\'s what a \"story\" tuple looks like (input, query, answer):')\nprint(train_stories[0])\nprint('-')\nprint('Vectorizing the word sequences...')\n\nword_idx = dict((c, i + 1) for i, c in enumerate(vocab))\ninputs_train, queries_train, answers_train = vectorize_stories(train_stories, word_idx, story_maxlen, query_maxlen)\ninputs_test, queries_test, answers_test = vectorize_stories(test_stories, word_idx, story_maxlen, query_maxlen)\n\nprint('-')\nprint('inputs: integer tensor of shape (samples, max_length)')\nprint('inputs_train shape:', inputs_train.shape)\nprint('inputs_test shape:', inputs_test.shape)\nprint('-')\nprint('queries: integer tensor of shape (samples, max_length)')\nprint('queries_train shape:', queries_train.shape)\nprint('queries_test shape:', queries_test.shape)\nprint('-')\nprint('answers: binary (1 or 0) tensor of shape (samples, vocab_size)')\nprint('answers_train shape:', answers_train.shape)\nprint('answers_test shape:', answers_test.shape)\nprint('-')\nprint('Compiling...')\n\n# embed the input sequence into a sequence of vectors\ninput_encoder_m = Sequential()\ninput_encoder_m.add(Embedding(input_dim=vocab_size,\n output_dim=64,\n input_length=story_maxlen))\n# output: (samples, story_maxlen, embedding_dim)\n# embed the question into a single vector\nquestion_encoder = Sequential()\nquestion_encoder.add(Embedding(input_dim=vocab_size,\n output_dim=64,\n input_length=query_maxlen))\n# output: (samples, query_maxlen, embedding_dim)\n# compute a 'match' between input sequence elements (which are vectors)\n# and the question vector\nmatch = Sequential()\nmatch.add(Merge([input_encoder_m, question_encoder],\n mode='dot',\n dot_axes=[(2,), (2,)]))\n# output: (samples, story_maxlen, query_maxlen)\n# embed the input into a single vector with size = story_maxlen:\ninput_encoder_c = Sequential()\ninput_encoder_c.add(Embedding(input_dim=vocab_size,\n output_dim=query_maxlen,\n input_length=story_maxlen))\n# output: (samples, story_maxlen, query_maxlen)\n# sum the match vector with the input vector:\nresponse = Sequential()\nresponse.add(Merge([match, input_encoder_c], mode='sum'))\n# output: (samples, story_maxlen, query_maxlen)\nresponse.add(Permute((2, 1))) # output: (samples, query_maxlen, story_maxlen)\n\n# concatenate the match vector with the question vector,\n# and do logistic regression on top\nanswer = Sequential()\nanswer.add(Merge([response, question_encoder], mode='concat', concat_axis=-1))\n# the original paper uses a matrix multiplication for this reduction step.\n# we choose to use a RNN instead.\nanswer.add(LSTM(64))\n# one regularization layer -- more would probably be needed.\nanswer.add(Dropout(0.25))\nanswer.add(Dense(vocab_size))\n# we output a probability distribution over the vocabulary\nanswer.add(Activation('softmax'))\n\nanswer.compile(optimizer='rmsprop', loss='categorical_crossentropy')\n# Note: you could use a Graph model to avoid repeat the input twice\nanswer.fit([inputs_train, queries_train, inputs_train], answers_train,\n batch_size=32,\n nb_epoch=70,\n show_accuracy=True,\n validation_data=([inputs_test, queries_test, inputs_test], answers_test))\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TatsuyaShirakawa/torchemb
[ "b72912c7602537f368c16fdeb2bb6cf177b742be" ]
[ "scripts/poincare_embeddings.py" ]
[ "'''\nA rouch implementation of the following paper\n\nM. Nickel+, \"Poincaré Embeddings for Learning Hierarchical Representations\", NeurIPS2017\nhttps://arxiv.org/pdf/1705.08039.pdf\n'''\nimport argparse\nfrom pathlib import Path\nimport itertools\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import (IterableDataset,\n RandomSampler,\n DataLoader)\nfrom gensim.corpora import Dictionary\nfrom tqdm import tqdm\nfrom torchemb.poincare_ball import PoincareBallEmbedding, PoincareBall\n\n\nparser = argparse.ArgumentParser('Poincare Embeddings')\nparser.add_argument('data_file', type=Path)\nparser.add_argument('result_file', type=Path)\nparser.add_argument('-e', '--embedding_dim', default=10, type=int)\nparser.add_argument('-m', '--max_epoch', default=200, type=int)\nparser.add_argument('-s', '--samples_per_iter', default=10000, type=int)\nparser.add_argument('-b', '--batch_size', default=512, type=int)\nparser.add_argument('-n', '--neg_size', default=10, type=int)\nparser.add_argument('-c', default=1, type=float)\nparser.add_argument('--lr', default=1.0e-3, type=float)\nparser.add_argument('--momentum', default=0.9, type=float)\nparser.add_argument('--seed', default=0, type=int)\nargs = parser.parse_args()\nprint(args)\n\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\n\n\ndef load_data(data_file):\n data_file = Path(data_file)\n pairs = []\n with data_file.open() as fin:\n for line in fin:\n a, b = line.strip().split('\\t')\n pairs.append((a, b))\n d = Dictionary(pairs)\n pairs = np.asarray([d.doc2idx(pair) for pair in pairs])\n return d, pairs\n\n\ndictionary, pairs = load_data(args.data_file)\nprint(len(dictionary), len(pairs))\n\n\nclass Dataset(IterableDataset):\n def __init__(self, pairs, neg_size):\n self.pairs = pairs\n self.neg_size = neg_size\n self.pair_sampler = RandomSampler(list(range(len(self.pairs))), replacement=True)\n\n def __iter__(self):\n pair_iter = itertools.cycle(iter(self.pair_sampler))\n while True:\n idx = next(pair_iter)\n x, y = self.pairs[idx]\n ys = [y] + [self.pairs[next(pair_iter)][1] for _ in range(self.neg_size - 1)]\n yield x, torch.LongTensor(ys)\n\n\ndata = DataLoader(Dataset(pairs, args.neg_size),\n batch_size=args.batch_size)\n\nembeddings = PoincareBallEmbedding(len(dictionary), args.embedding_dim, c=args.c)\nmanifold = PoincareBall(c=args.c)\n\nloss = nn.CrossEntropyLoss()\nwarmup_rate = 100\nlr = args.lr * (args.batch_size ** 0.5) / (args.embedding_dim ** 0.5)\noptimizer = optim.Adam(embeddings.parameters(), lr=lr)\nlr_scheduler = optim.lr_scheduler.ExponentialLR(optimizer,\n gamma=math.exp(math.log(0.01) / args.max_epoch))\n\n\ndef train(embeddings, loss, optimizer, data, samples_per_iter):\n embeddings.train()\n data_iter = iter(data)\n avg_loss_ = 0\n N = samples_per_iter // args.batch_size\n for i in tqdm(range(N)):\n idx1, idx2 = next(data_iter)\n x, ys = embeddings(idx1), embeddings(idx2)\n assert(not torch.any(torch.isnan(x)))\n assert(not torch.any(torch.isnan(ys)))\n ds = manifold.distance(x[:, None, :].expand_as(ys), ys)\n logits = -ds\n loss_ = loss(logits, torch.zeros(len(logits), dtype=torch.long))\n optimizer.zero_grad()\n loss_.backward()\n optimizer.step()\n avg_loss_ += loss_.item()\n avg_loss_ /= N\n print('train loss: {:.5f}'.format(avg_loss_))\n\n\ndef save(embeddings, dictionary, result_file):\n embeddings.eval()\n result_file = Path(result_file)\n result_file.parent.mkdir(parents=True, exist_ok=True)\n with torch.no_grad():\n with result_file.open('w') as fout:\n for i, c in sorted(dictionary.dfs.items()):\n e = embeddings(torch.LongTensor([i]))[0]\n print(dictionary[i], *[_.item() for _ in e], sep='\\t', file=fout)\n\n\nfor epoch in range(args.max_epoch):\n print('epoch:', epoch + 1, '/', args.max_epoch)\n train(embeddings, loss, optimizer, data, args.samples_per_iter)\n lr_scheduler.step()\n save(embeddings, dictionary, args.result_file)\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.LongTensor", "torch.isnan", "numpy.random.seed", "torch.manual_seed", "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kbots-dga/ml_classificator
[ "0163141de7389825787b9813019582be98d0f266" ]
[ "app.py" ]
[ "import streamlit as st\nimport plotly.express as px\nimport pandas as pd\nimport pickle\nimport os\nimport base64\nfrom io import BytesIO\nfrom datetime import datetime\n\n\ndef to_excel(df):\n output = BytesIO()\n writer = pd.ExcelWriter(output, engine='xlsxwriter')\n df.to_excel(writer, index=False, sheet_name='Sheet1')\n writer.save()\n processed_data = output.getvalue()\n return processed_data\n\n\ndef get_table_download_link(df):\n val = to_excel(df)\n b64 = base64.b64encode(val)\n date_now = datetime.utcnow()\n file_name = f'data_resultado-{date_now.strftime(\"%Y%m%d%H%M%S\")}.xlsx'\n link_download = f\"\"\" <a href=\"data:application/octet-stream;base64,{b64.decode()}\" download=\"{file_name}\">Download xlsx file</a> \"\"\"\n return link_download\n\n\ndef plot_graph(df_graph):\n fig = px.bar(\n df_graph,\n x='Labels',\n y='Descrição',\n # text='Text test',\n title='Test',\n labels={\n \"Labels\": \"Labels\",\n \"Descrição\": 'Número de coisas'\n },\n # width=1400,\n height=500\n )\n return fig\n\n\ndef main(classificador):\n st.title('Model')\n process_file = st.file_uploader(\n \"Faça o upload do arquivo no campo abaixo.\",\n type=[\"csv\", \"xlsx\"],\n accept_multiple_files=False\n )\n\n print(process_file)\n print(os.environ.get('TOKEN'))\n if process_file != None:\n if process_file.name.endswith('.csv'):\n df = pd.read_csv(\n process_file, header=0, skip_blank_lines=True, skipinitialspace=True, encoding='latin-1')\n\n elif process_file.name.endswith('.xlsx'):\n df = pd.read_excel(\n process_file, engine=\"openpyxl\")\n\n with st.empty():\n st.write('Fazendo as predições ...')\n df['Labels'] = classificador.predict(\n df[\"Descrição\"].astype(\"unicode\"))\n st.write('Predições feitas com sucesso !!!')\n\n st.dataframe(df.head(20))\n\n df_graph = df.groupby(['Labels'], as_index=False)['Descrição'].count()\n df_graph.sort_values(by=['Descrição'], inplace=True, ascending=False)\n print(df_graph)\n st.plotly_chart(plot_graph(df_graph), use_container_width=True)\n st.text('Gerando link para download ...')\n st.markdown(get_table_download_link(df), unsafe_allow_html=True)\n st.success('Link gerado com sucesso.')\n\n\nif __name__ == '__main__':\n classificador = pickle.load(open(\"modelo_final.pkl\", \"rb\"))\n main(classificador)\n" ]
[ [ "pandas.read_excel", "pandas.read_csv", "pandas.ExcelWriter" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
tomkimpson/ML4L
[ "ffa8360cb80df25bd6af4fa5cc39b42bd6f405cd", "ffa8360cb80df25bd6af4fa5cc39b42bd6f405cd" ]
[ "legacy/legacy_scripts/legacy/.ipynb_checkpoints/train_and_predict-checkpoint.py", "pipeline/raw_data_processor/prep_for_ML.py" ]
[ "\n\n\n\n\nimport tensorflow as tf\nimport os\nimport time\nimport json\nimport pandas as pd\n\n\n\n\"\"\"\nScript to train a sequential NN.\nTakes a df, filters based on `condition` (default None), and separates into test/train based on time\nNN trains on training data, all results output to disk\n\"\"\"\n\n\ndef train_test_split(df,filter_condition,train_condition, test_condition,features,targets):\n \n \n \"\"\"\n Separate df into a train and test set.\n Returns training and testing dfs as well as split into inputs/outputs \n \"\"\"\n \n #Filter dataset\n if filter_condition is not None:\n df_filtered = df.query(filter_condition)\n else:\n df_filtered = df\n \n #Select train/test data\n training_data = df_filtered.query(train_condition)\n test_data = df_filtered.query(test_condition)\n \n \n #Separate into features/targets\n\n x_train = training_data[features]\n y_train = training_data[targets]\n\n x_test = test_data[features]\n y_test = test_data[targets]\n \n \n return x_train,y_train,x_test,y_test,training_data, test_data #\n \n \n\n\ndef create_normalizer_layer(x_train):\n #Create a normaliser layer\n print ('Creating a normalization layer')\n normalizer = tf.keras.layers.Normalization(axis=-1)\n normalizer.adapt(x_train)\n \n return normalizer\n\ndef train_NN(x_train,y_train,normalizer):\n\n\n #Check GPU available\n print(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n\n\n #Create a basic NN model\n model = tf.keras.Sequential([\n normalizer,\n tf.keras.layers.Dense(int(len(features)/2), activation='relu',input_shape=(len(features),),name='layer1'),\n tf.keras.layers.Dense(1, name='output')\n ])\n\n #Compile it\n print ('Compiling model')\n model.compile(optimizer='adam',\n loss='mse',\n metrics=['accuracy'])\n \n\n \n #Train it\n print('Training model')\n history = model.fit(x_train, y_train, epochs=100, batch_size=10000) \n \n \n return history, model\n\n\ndef write_outputs(output_path,model,history,x_train,y_train,x_test,y_test,df_train,df_test):\n\n print ('Writing outputs to dir: ', fout)\n id = int(time.time())\n fout = output_path+f'ML_{str(id)}/'\n os.makedirs(fout)\n print ('Writing outputs to dir: ', fout)\n\n\n \n #NN\n model.save(fout+'trained_model') \n history_dict = history.history\n json.dump(history_dict, open(fout+'history.json', 'w'))\n \n #Data\n #Probaby overkill saving all of these\n x_train.to_pickle(fout + \"x_train.pkl\") \n y_train.to_pickle(fout + \"y_train.pkl\") \n x_test.to_pickle(fout + \"x_test.pkl\") \n x_test.to_pickle(fout + \"y_test.pkl\")\n df_train.to_pickle(fout + \"df_train.pkl\") \n df_test.to_pickle(fout + \"df_test.pkl\") \n\n\n\n \n \n\n\ndef pipeline(input_file,output_path,filter_condition,train_condition, test_condition,features):\n \n \n #Load the data\n print('Loading the data')\n df = pd.read_pickle(input_file)\n\n \n #Process into train/test\n targets = ['MODIS_LST']\n x_train,y_train,x_test,y_test,df_train,df_test = train_test_split(df,filter_condition,train_condition, test_condition,features,targets)\n\n \n \n #Train NN\n normalizer = create_normalizer_layer(x_train)\n history,model = train_NN(x_train,y_train,normalizer)\n \n \n #Save trained NN in new dir, along with train/test sets\n write_outputs(output_path,model,history,x_train,y_train,x_test,y_test,df_train,df_test)\n\n \n \n \n#Parameters\n\n#IO\ninput_file = '/network/group/aopp/predict/TIP016_PAXTON_RPSPEEDY/ML4L/ECMWF_files/raw/MODIS_ERA_joined_data_averaged.pkl'\noutput_path = '/network/group/aopp/predict/TIP016_PAXTON_RPSPEEDY/ML4L/'\n\n\n\n#Pre Processing\nfilter_condition = None\ntrain_condition = 'time < \"2019-01-01 00:00:00\"'\ntest_condition = 'time >= \"2020-01-01 00:00:00\"'\nfeatures = ['sp', 'msl', 'u10', 'v10','t2m',\n 'aluvp', 'aluvd', 'alnip', 'alnid', 'cl',\n 'cvl', 'cvh', 'slt', 'sdfor', 'z', 'sd', 'sdor', 'isor', 'anor', 'slor',\n 'd2m', 'lsm', 'fal'] \n\n\n\n\n#Go\npipeline(input_file,output_path,filter_condition,train_condition, test_condition,features)\n\n", "#Internal\nfrom telnetlib import VT3270REGIME\nfrom xml.etree.ElementInclude import include\nfrom utils.config import Config \n\n#external\nimport glob\nimport pandas as pd \nimport numpy as np\nimport xarray as xr\nimport sys\nclass PrepareMLData():\n\n \"\"\"\n Class which takes the joined monthly ERA-MODIS data and puts it in a 'nice form'\n ready for training a model.\n\n Also calculates the \"delta features\" i.e. V20 - V15 for the time constant features\n \n 'Greedy' method produce a single file for each train/validate/test.\n\n 'Sensible' method still needs to be converted from scripts\n \"\"\"\n\n def __init__(self,cfg): \n self.config = Config.from_json(cfg) # Configuration file\n \n #Train/Validate/Test\n self.training_years = self.config.data.training_years\n self.validation_years = self.config.data.validation_years\n self.test_years = self.config.data.test_years\n\n #ERA/MODIS files to take in\n self.path_to_input_data = self.config.data.path_to_joined_ERA_MODIS_files\n self.IO_prefix = self.config.data.IO_prefix\n \n #Extra bonus data that needs to be joined on\n self.bonus_data = self.config.data.bonus_data\n\n #Categorise different columns\n self.xt = self.config.data.list_of_meta_features #Time/space\n self.time_variable_features = self.config.data.list_of_time_variable_features\n self.V15_features = self.config.data.list_of_V15_features\n self.V20_features = self.config.data.list_of_V20_features\n self.bonus_features = self.config.data.list_of_bonus_features\n self.target = self.config.data.target_variable\n self.columns_to_load = self.time_variable_features + self.V15_features + self.V20_features + self.bonus_features + self.target\n\n #Declare global emptys\n self.normalisation_mean = None \n self.normalisation_std = None \n self.drop_cols = None \n\n #Checks\n assert len(self.V15_features) == len(self.V20_features)\n assert len(self.target) == 1 \n\n\n\n def _calculate_delta_fields(self,df):\n \n \"\"\"Function to determine all the delta fields: V20 - V15 \n V20 fields is reassigned to a delta field.\"\"\"\n \n for i in range(len(self.V15_features)):\n v15 = self.V15_features[i]\n v20 = self.V20_features[i]\n assert v20.split('_')[0] == v15.split('_')[0]\n\n df[v20] = df[v20] - df[v15] #Reassign the v20 fields to all be delta fields \n \n return df \n\n\n\n\n\n def _process_year(self,years_to_process,include_xt):\n\n \"\"\"\n Function to process a directory of monthly files and write them to a single file.\n Also calculates normalisation over the entire training set and determines delta corrections\n Writes a single file to directory/\n \"\"\"\n\n pop_cols = self.target+self.xt # These columns will not be popped of and won't be normalized, but will be saved to file for the test set\n unneeded_columns = ['latitude_MODIS','longitude_MODIS', 'heightAboveGround', 'H_distance_km'] # We have no need of these cols. They will be loaded but immediatley dropped\n\n \n \n #Load any extra data that we want to join on\n saline_ds = xr.open_dataset(self.bonus_data,engine='cfgrib',backend_kwargs={'indexpath': ''})\n saline_ds = saline_ds.assign_coords({\"longitude\": (((saline_ds.longitude + 180) % 360) - 180)})\n saline_ds = saline_ds.cl.rename(f'cl_saline_max') # This is now a data array\n saline_df = saline_ds.to_dataframe().reset_index()[['latitude','longitude','cl_saline_max']]\n \n\n monthly_files = []\n for i in years_to_process:\n files = glob.glob(self.path_to_input_data+self.IO_prefix+f'*_{i}_*.parquet')\n monthly_files.append(files)\n \n monthly_files = sorted([item for sublist in monthly_files for item in sublist]) \n\n dfs_features = [] #array to hold dfs which have features\n dfs_targets = []\n for m in monthly_files:\n print ('Loading file f:',m)\n df = pd.read_parquet(m).reset_index()\n df=df.drop(unneeded_columns,axis=1)\n\n #Pass monthly clake as a v20 correction\n df['clake_monthly_value'] = df['clake_monthly_value'] - df['cl_v20'] \n\n\n #assert (df['clake_monthly_value'] > 0).all() # the monthly cl corrections should always be positive\n\n #Calculate delta fields\n df = self._calculate_delta_fields(df)\n\n #Join on bonus saline max extent data\n df = pd.merge(df, saline_df, how='left', left_on=['latitude_ERA', 'longitude_ERA'], right_on=['latitude','longitude'], suffixes=(None,)).drop(['latitude', 'longitude'],axis=1) # merge and drop lat/long coordinates from the join\n\n df_target = pd.concat([df.pop(x) for x in pop_cols], axis=1)\n df_target['skt_unnormalised'] = df['skt']\n \n #Append \n dfs_features.append(df)\n dfs_targets.append(df_target)\n \n \n print('All dfs loaded and processed. Now concatenate together.')\n df_features = pd.concat(dfs_features)\n df_targets = pd.concat(dfs_targets)\n\n # Monthly cl corrections should always be positive. Set to zero if not\n df_features['clake_monthly_value'] = df_features['clake_monthly_value'].clip(lower=0)\n\n\n if (self.normalisation_mean is None) & (self.normalisation_std is None): # On the first pass when dealing with the training set\n\n # Check for useless columns and drop them\n print ('Checking for useless cols')\n columns_with_zero_variance = df_features.nunique()[df_features.nunique() == 1].index.values\n print (f'The following features have zero variance in year {years_to_process} and will be dropped')\n print (columns_with_zero_variance)\n self.drop_cols = columns_with_zero_variance\n\n\n\n\n print ('Calculating normalisation parameters for years:', years_to_process)\n #If we dont have any normalisation parameters already \n self.normalisation_mean = df_features.mean()\n self.normalisation_std = df_features.std()\n\n\n #Normalise training features using the pre calculated terms\n df_features = (df_features-self.normalisation_mean)/self.normalisation_std\n\n #Get rid of columns with zero variance\n df_features = df_features.drop(self.drop_cols, axis=1)\n \n #IF not the test set, only carry the MODIS_LST\n if not include_xt:\n df_targets = df_targets[self.target] \n\n #Concat all together\n df_out = pd.concat([df_features,df_targets],axis=1)\n\n \n # Save it to disk\n fout = self.path_to_input_data + '-'.join(years_to_process) + '_RML.parquet' # Possible to save multiple yeats to one file, might be more sensible to just process year-by-year\n print ('Saving to:',fout)\n df_out.to_parquet(fout,compression=None)\n\n\n\n def greedy_preprocessing(self):\n\n \"\"\"\n Process the ERA-MODIS data in a greedy manner, ignoring any potential future restrictions on memory\n \"\"\"\n\n print ('Prepare training data')\n self._process_year(self.training_years,include_xt=True) \n\n \n print ('Prepare validation data')\n self._process_year(self.validation_years,include_xt=True) \n \n print ('Prepare test data')\n self._process_year(self.test_years,include_xt=True) \n\n\n def sensible_preprocessing(self):\n\n \"\"\"\n Process the ERA-MODIS data in a sensible memory-lite way, using TFRecords\n \"\"\"" ]
[ [ "tensorflow.keras.layers.Dense", "pandas.read_pickle", "tensorflow.config.list_physical_devices", "tensorflow.keras.layers.Normalization" ], [ "pandas.read_parquet", "pandas.concat", "pandas.merge" ] ]
[ { "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": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
paul-ang/nas-segm-pytorch
[ "e83704b6cdac6426d6ee51059f82cf650238677c", "e83704b6cdac6426d6ee51059f82cf650238677c" ]
[ "src/utils/solvers.py", "src/data/hsi_dataset.py" ]
[ "\"\"\"Initialising Optimisers\"\"\"\n\nimport torch\n\n\ndef create_optimisers(\n optim_enc,\n optim_dec,\n lr_enc,\n lr_dec,\n mom_enc,\n mom_dec,\n wd_enc,\n wd_dec,\n param_enc,\n param_dec,\n):\n \"\"\"Create optimisers for encoder, decoder\n\n Args:\n optim_enc (str) : type of optimiser for encoder\n optim_dec (str) : type of optimiser for decoder\n lr_enc (float) : learning rate for encoder\n lr_dec (float) : learning rate for decoder\n mom_enc (float) : momentum for encoder\n mom_dec (float) : momentum for decoder\n wd_enc (float) : weight decay for encoder\n wd_dec (float) : weight decay for decoder\n param_enc (torch.parameters()) : encoder parameters\n param_dec (torch.parameters()) : decoder parameters\n\n Returns optim_enc, optim_dec (torch.optim)\n\n \"\"\"\n if optim_enc == \"sgd\":\n optim_enc = torch.optim.SGD(\n param_enc, lr=lr_enc, momentum=mom_enc, weight_decay=wd_enc\n )\n elif optim_enc == \"adam\":\n optim_enc = torch.optim.Adam(param_enc, lr=lr_enc, weight_decay=wd_enc)\n else:\n raise ValueError(\"Unknown Encoder Optimiser: {}\".format(optim_enc))\n\n if optim_dec == \"sgd\":\n optim_dec = torch.optim.SGD(\n param_dec, lr=lr_dec, momentum=mom_dec, weight_decay=wd_dec\n )\n elif optim_dec == \"adam\":\n optim_dec = torch.optim.Adam(param_dec, lr=lr_dec, weight_decay=wd_dec)\n else:\n raise ValueError(\"Unknown Decoder Optimiser: {}\".format(optim_dec))\n return optim_enc, optim_dec\n", "# Standard library imports\nimport numpy as np\nfrom numpy import loadtxt\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n# Third party imports\nimport cv2\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset, random_split\n\n\nclass HSIDataset(Dataset):\n def __init__(self, root_dir, txt_files, classes=[0, 1, 2, 3, 4],\n n_cutoff_imgs=None, conv_dims=2):\n \"\"\"\n :param root_dir: root directory to the dataset folder, e.g ../02-Data/UOW-HSI/\n :param txt_files: text files contain filenames of BMP (ground-truth) files\n The hsi file has the same filename but with the extension '.raw'\n :param classes: list of classes in the segmentation problem (classes must start from 0)\n e.g. [0, 1, 2, 3, 4, 5]\n :param n_dims: dimensions of the convolutions\n + n_dims = 2, return x with a size of (n_bands, H, W).\n + n_dims = 3, return x with a size of (1, n_bands, H, W).\n (# Add a new axis in the first dimension of the original x)\n :param n_cutoff_imgs: maximum number of used images in each text file\n \"\"\"\n super(HSIDataset, self).__init__()\n self.classes = classes\n self.txt_files = txt_files\n self.root_dir = root_dir\n self.conv_dims = conv_dims\n\n if (not isinstance(n_cutoff_imgs, int)) or (n_cutoff_imgs <= 0):\n n_cutoff_imgs = None\n\n # Get filenames of the training images stored in txt_files\n if isinstance(txt_files, str):\n txt_files = [txt_files]\n self.training_imgs = []\n for file in txt_files:\n imgs = list(loadtxt(file, dtype=np.str)[:n_cutoff_imgs])\n\n if len(self.training_imgs) == 0:\n self.training_imgs = imgs\n else:\n self.training_imgs = np.concatenate((self.training_imgs, imgs))\n\n def __len__(self):\n \"\"\"\n :return: the size of the dataset, i.e. the number of hsi images\n \"\"\"\n return len(self.training_imgs)\n\n def __getitem__(self, index):\n \"\"\"\n Read the an image from the training images\n :param index: index of the image in the list of training images\n :return: hsi image and ground-truth images\n + x: input hsi image of size (n_bands, H, W)\n + y_seg: ground-truth segmentation image of size (H, W)\n + y_oht: one-hot coding of the ground-truth image of size (n_classes, H, W)\n \"\"\"\n # Get the ground truth and raw files\n bmp_file = self.root_dir + '/' + self.training_imgs[index]\n raw_file = self.root_dir + '/' + self.training_imgs[index][:-4] + '.raw'\n\n # Read the hsi image\n x, _ = hsi_read_data(raw_file) # of size (H, W, n_bands)\n x = np.moveaxis(x, [0, 1, 2], [1, 2, 0]) # of size (n_bands, H, W)\n x = np.float32(x) # convert the input data into float32 datatype\n\n # Minmax normalization so x in range of [0,1]\n x = (x - np.min(x)) / (np.max(x) - np.min(x))\n\n if self.conv_dims == 3: # Add a new axis in the first dimension\n x = x[np.newaxis, ...] # of size (1, n_bands, H, W)\n\n # Read the ground-truth image\n bmp = Image.open(bmp_file)\n y_seg = np.array(bmp.getdata()).reshape(bmp.size[1], bmp.size[0]) # of size (H, W)\n\n # Convert the images into Pytorch tensors\n x = torch.Tensor(x) # of size (n_bands, H, W)\n y_seg = torch.as_tensor(y_seg, dtype=torch.long) # of size (H, W)\n\n return {'image': x, 'mask': y_seg}\n\n\ndef hsi_read_data(file_name, sorted=True):\n \"\"\"\n Read the image cube from the raw hyperspectral image file (.raw)\n :param file_name: file path of the raw hsi file\n :param sorted: bool value to sort the image cube in the ascending of wave_lengths\n :return: 2 params\n - img: image cube in the shape of [n_lines, n_samples, n_bands]\n - wave_lengths: list of wave lengths used to acquired the data\n \"\"\"\n # Get the information from the header file\n hdr_file = file_name[:-4] + '.hdr'\n n_samples, n_lines, n_bands, data_type, wave_lengths = hsi_read_header(hdr_file)\n\n # Open the raw file\n f = open(file_name, 'rb')\n # Read the data in the raw file\n data = np.frombuffer(f.read(), dtype=data_type)\n\n # Close the file\n f.close()\n\n # Reshape the data into the 3D formar of lines x bands x samples]\n img = data.reshape([n_lines, n_bands, n_samples])\n\n # Permute the image into the correct format lines x samples x bands\n img = np.moveaxis(img, [0, 1, 2], [0, 2, 1])\n\n if sorted:\n # Get the sorted indices of wave_lengths in the ascending order\n indx = np.argsort(wave_lengths)\n\n # Get the sorted wave_lengths\n wave_lengths = wave_lengths[indx]\n\n # Sort the image cube in the ascending order of wave_lengths\n img = img[:, :, indx]\n\n return img, wave_lengths\n\ndef hsi_read_header(file_name, verbose=False):\n \"\"\"\n Load the information of a hyperspectral image from a header file (.hdr)\n :param file_name: file path of the header hsi file\n :param verbose: bool value to display the result (defaul: False)\n :return: 5 params\n - n_samples: number of n_samples in the image (width)\n - lines: number of lines in the image (height)\n - bands: number of bands (wave lengths)\n - data_type: data type stored in the data file\n - wave_lengths: list of wave lengths used to acquired the data\n \"\"\"\n # Open a file for reading\n f = open(file_name, 'r+')\n\n # Read all the lines in the header file\n text = f.readlines()\n\n # Close the file\n f.close()\n\n n = 0\n while n < len(text):\n text_line = text[n].replace('\\n', '')\n # Get number of samples (width)\n if 'samples' in text_line:\n n_samples = int(text_line.split(' ')[-1])\n\n # Get number of lines (height)\n if 'lines' in text_line:\n n_lines = int(text_line.split(' ')[-1])\n\n # Get number of bands/wave lengths\n if 'bands' in text_line and not(' bands' in text_line):\n n_bands = int(text_line.split(' ')[-1])\n\n # Get the data type\n if 'data type' in text_line:\n data_type = int(text_line.split(' ')[-1])\n\n # Get the wave length values\n if 'Wavelength' in text_line:\n wave_lengths = np.zeros(n_bands)\n for k in range(n_bands):\n n = n + 1\n text_line = text[n].replace(',\\n', '').replace(' ', '')\n wave_lengths[k] = float(text_line)\n break\n n = n + 1\n\n # Convert the data_type into the string format\n if data_type == 1:\n data_type = 'uint8'\n elif data_type == 2:\n data_type = 'int16'\n elif data_type == 3:\n data_type = 'int32'\n elif data_type == 4:\n data_type = 'float32'\n elif data_type == 5:\n data_type = 'double'\n elif data_type == 12:\n data_type = 'uint16'\n elif data_type == 13:\n data_type = 'uint32'\n elif data_type == 14:\n data_type = 'int64'\n elif data_type == 15:\n data_type = 'uint64'\n\n if verbose: # display the outputs if it is necessary\n print('Image width = %d' % n_samples)\n print('Image height = %d' % n_lines)\n print('Bands = %d' % n_bands)\n print('Data type = %s' % data_type)\n\n return n_samples, n_lines, n_bands, data_type, wave_lengths\n\n\ndef convert_seg2onehot(y_seg, classes):\n \"\"\"\n Convert the segmentation image y into the one-hot code image\n :param y_seg: 2D array, a segmentation image with a size of H x W\n :param classes: list of classes in image y\n :return: one-hot code image of y with a size of n_classes x H x W\n \"\"\"\n y_onehot = np.zeros((len(classes), y_seg.shape[0], y_seg.shape[1]))\n\n for k, class_label in enumerate(classes):\n y_onehot[k, :, :][y_seg == class_label] = 1\n\n return y_onehot\n\n\ndef convert_prob2seg(y_prob, classes):\n \"\"\"\n Convert the class-probability image into the segmentation image\n :param y_prob: class-probability image with a size of n_classes x H x W\n :param classes: list of classes in image y\n :return: 2D array, a segmentation image with a size of H x W\n \"\"\"\n y_class = np.argmax(y_prob, axis=0)\n y_seg = np.zeros((y_prob.shape[1], y_prob.shape[2]))\n\n for k, class_label in enumerate(classes):\n # Find indices in y_class whose pixels are k\n indx = np.where(y_class == k)\n if len(indx[0] > 0):\n y_seg[indx] = class_label\n\n return y_seg\n\n\nif __name__ == \"__main__\":\n HSIDataset('/projects/datasets/hsi/UOW-HSI',\n txt_files=['/projects/datasets/hsi/uow-hsi-3125/P2.txt', '/projects/datasets/hsi/uow-hsi-3125/P3.txt'])\n\n\n\n" ]
[ [ "torch.optim.Adam", "torch.optim.SGD" ], [ "torch.Tensor", "numpy.min", "numpy.concatenate", "numpy.max", "numpy.argmax", "numpy.float32", "numpy.moveaxis", "numpy.argsort", "numpy.zeros", "numpy.where", "numpy.loadtxt", "torch.as_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rpalovics/Alpenglow
[ "7a15d5c57b511787379f095e7310e67423159fa0" ]
[ "examples/external_models/turicreate/run_turicreate.py" ]
[ "import os\nos.environ[\"OMP_NUM_THREADS\"] = \"10\"\n\nimport sys\nimport pandas as pd\nimport numpy as np\nimport turicreate as tc\n\n\nfor i in range(1, 14):\n print(\"running batch %d\" % i)\n batch = pd.read_csv(\"batches/batch_%d_train.dat\" % i)\n test_users = pd.read_csv(\"batches/batch_%d_test.dat\" % i)\n model = tc.ranking_factorization_recommender.create(\n tc.SFrame(batch),\n 'user',\n 'item',\n num_factors=10,\n verbose=True,\n solver='ials',\n max_iterations=50,\n ials_confidence_scaling_factor=30\n )\n results = model.recommend(users=test_users.user.values, k=100, exclude_known=True, verbose=False)\n results.to_dataframe()[['user', 'item', 'rank']].to_csv('batches/batch_%d_predictions.dat' % i, sep=' ', header=False, index=False)" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
smarsu/facenet
[ "a0fa3ffe32e295b4cc980a4a178593cc7f1bad12" ]
[ "compare.py" ]
[ "# --------------------------------------------------------\n# SMNet FaceNet\n# Licensed under The MIT License [see LICENSE for details]\n# Copyright 2019 smarsu. All Rights Reserved.\n# --------------------------------------------------------\n\nimport os.path as osp\nimport numpy as np\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\nfrom euclidean import euclidean_distance\n\nEPS = 1e-12\n\n\ndef load_feature_map_from_txt(path_txt):\n \"\"\"\"\"\"\n with open(path_txt, 'r') as fb:\n lines = fb.readlines()\n feature_map = {}\n for line in lines:\n line = line.strip().split()\n name = line[0]\n feature = [float(v) for v in line[1:]]\n feature_map[name] = np.array(feature, dtype=np.float64)\n return feature_map\n\n\ndef load_pairs(pair_path):\n with open(pair_path, 'r') as fb:\n lfw_root = '/datasets/lfw_detected'\n lines = fb.readlines()\n pairs = []\n for line in lines:\n fst, snd, match = line.strip().split()\n fst = osp.join(lfw_root, fst)\n snd = osp.join(lfw_root, snd)\n pairs.append([fst, snd, int(match)])\n return pairs\n\n\ndef l2_norm(x):\n \"\"\"\n Args:\n x: ndarray, [n, feature_len]\n \"\"\"\n x = np.array(x, dtype=np.float64)\n return x / (np.sqrt(np.sum(np.square(x), axis=-1, keepdims=True)) + EPS)\n\n\ndef cosine_similarity(a, b):\n \"\"\"\n Args:\n a: ndarray, [feature_len]\n b: ndarray, [feature_len]\n \"\"\"\n a = np.array(a, dtype=np.float64)\n b = np.array(b, dtype=np.float64)\n return np.sum(a * b)\n\n\ndef auc(scores, labels):\n \"\"\"\"\"\"\n return metrics.roc_auc_score(labels, scores)\n\n\ndef roc(scores, labels):\n \"\"\"\"\"\"\n fpr, tpr, thresholds = metrics.roc_curve(labels, scores)\n plt.plot(fpr, tpr)\n plt.savefig('roc.png')\n\n\ndef main():\n feature_map = load_feature_map_from_txt('features.txt')\n feature_map = {k: l2_norm(v) for k, v in feature_map.items()}\n\n pairs = load_pairs('parsed_pair.txt')\n scores = []\n labels = []\n for fst, snd, match in pairs:\n labels.append(match)\n if fst not in feature_map:\n scores.append(1)\n print('WARNING: not found', fst)\n continue\n elif snd not in feature_map:\n scores.append(1)\n print('WARNING: not found', snd)\n continue\n score = 2 - euclidean_distance(feature_map[fst], feature_map[snd])\n scores.append(score)\n\n print(scores)\n print(labels)\n\n print(min(scores))\n print(max(scores))\n \n print(auc(scores, labels))\n roc(scores, labels)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.square", "sklearn.metrics.roc_auc_score", "sklearn.metrics.roc_curve", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "numpy.array", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Ombarus/python_env
[ "4615976a51aa4f02206f5e03fc091b088d3273fc", "4615976a51aa4f02206f5e03fc091b088d3273fc" ]
[ "python35/Lib/site-packages/sklearn/linear_model/base.py", "python35/Lib/site-packages/sklearn/linear_model/ridge.py" ]
[ "\"\"\"\nGeneralized Linear models.\n\"\"\"\n\n# Author: Alexandre Gramfort <[email protected]>\n# Fabian Pedregosa <[email protected]>\n# Olivier Grisel <[email protected]>\n# Vincent Michel <[email protected]>\n# Peter Prettenhofer <[email protected]>\n# Mathieu Blondel <[email protected]>\n# Lars Buitinck\n# Maryan Morel <[email protected]>\n# Giorgio Patrini <[email protected]>\n# License: BSD 3 clause\n\nfrom __future__ import division\nfrom abc import ABCMeta, abstractmethod\nimport numbers\nimport warnings\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy import linalg\nfrom scipy import sparse\n\nfrom ..externals import six\nfrom ..externals.joblib import Parallel, delayed\nfrom ..base import BaseEstimator, ClassifierMixin, RegressorMixin\nfrom ..utils import check_array, check_X_y, deprecated, as_float_array\nfrom ..utils.validation import FLOAT_DTYPES\nfrom ..utils import check_random_state\nfrom ..utils.extmath import safe_sparse_dot\nfrom ..utils.sparsefuncs import mean_variance_axis, inplace_column_scale\nfrom ..utils.fixes import sparse_lsqr\nfrom ..utils.seq_dataset import ArrayDataset, CSRDataset\nfrom ..utils.validation import check_is_fitted\nfrom ..exceptions import NotFittedError\nfrom ..preprocessing.data import normalize as f_normalize\n\n# TODO: bayesian_ridge_regression and bayesian_regression_ard\n# should be squashed into its respective objects.\n\nSPARSE_INTERCEPT_DECAY = 0.01\n# For sparse data intercept updates are scaled by this decay factor to avoid\n# intercept oscillation.\n\n\ndef make_dataset(X, y, sample_weight, random_state=None):\n \"\"\"Create ``Dataset`` abstraction for sparse and dense inputs.\n\n This also returns the ``intercept_decay`` which is different\n for sparse datasets.\n \"\"\"\n\n rng = check_random_state(random_state)\n # seed should never be 0 in SequentialDataset\n seed = rng.randint(1, np.iinfo(np.int32).max)\n\n if sp.issparse(X):\n dataset = CSRDataset(X.data, X.indptr, X.indices, y, sample_weight,\n seed=seed)\n intercept_decay = SPARSE_INTERCEPT_DECAY\n else:\n dataset = ArrayDataset(X, y, sample_weight, seed=seed)\n intercept_decay = 1.0\n\n return dataset, intercept_decay\n\n\n@deprecated(\"sparse_center_data was deprecated in version 0.18 and will be \"\n \"removed in 0.20. Use utilities in preprocessing.data instead\")\ndef sparse_center_data(X, y, fit_intercept, normalize=False):\n \"\"\"\n Compute information needed to center data to have mean zero along\n axis 0. Be aware that X will not be centered since it would break\n the sparsity, but will be normalized if asked so.\n \"\"\"\n if fit_intercept:\n # we might require not to change the csr matrix sometimes\n # store a copy if normalize is True.\n # Change dtype to float64 since mean_variance_axis accepts\n # it that way.\n if sp.isspmatrix(X) and X.getformat() == 'csr':\n X = sp.csr_matrix(X, copy=normalize, dtype=np.float64)\n else:\n X = sp.csc_matrix(X, copy=normalize, dtype=np.float64)\n\n X_offset, X_var = mean_variance_axis(X, axis=0)\n if normalize:\n # transform variance to std in-place\n X_var *= X.shape[0]\n X_std = np.sqrt(X_var, X_var)\n del X_var\n X_std[X_std == 0] = 1\n inplace_column_scale(X, 1. / X_std)\n else:\n X_std = np.ones(X.shape[1])\n y_offset = y.mean(axis=0)\n y = y - y_offset\n else:\n X_offset = np.zeros(X.shape[1])\n X_std = np.ones(X.shape[1])\n y_offset = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype)\n\n return X, y, X_offset, y_offset, X_std\n\n\n@deprecated(\"center_data was deprecated in version 0.18 and will be removed in \"\n \"0.20. Use utilities in preprocessing.data instead\")\ndef center_data(X, y, fit_intercept, normalize=False, copy=True,\n sample_weight=None):\n \"\"\"\n Centers data to have mean zero along axis 0. This is here because\n nearly all linear models will want their data to be centered.\n If sample_weight is not None, then the weighted mean of X and y\n is zero, and not the mean itself\n \"\"\"\n X = as_float_array(X, copy)\n if fit_intercept:\n if isinstance(sample_weight, numbers.Number):\n sample_weight = None\n if sp.issparse(X):\n X_offset = np.zeros(X.shape[1])\n X_std = np.ones(X.shape[1])\n else:\n X_offset = np.average(X, axis=0, weights=sample_weight)\n X -= X_offset\n # XXX: currently scaled to variance=n_samples\n if normalize:\n X_std = np.sqrt(np.sum(X ** 2, axis=0))\n X_std[X_std == 0] = 1\n X /= X_std\n else:\n X_std = np.ones(X.shape[1])\n y_offset = np.average(y, axis=0, weights=sample_weight)\n y = y - y_offset\n else:\n X_offset = np.zeros(X.shape[1])\n X_std = np.ones(X.shape[1])\n y_offset = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype)\n return X, y, X_offset, y_offset, X_std\n\n\ndef _preprocess_data(X, y, fit_intercept, normalize=False, copy=True,\n sample_weight=None, return_mean=False):\n \"\"\"\n Centers data to have mean zero along axis 0. If fit_intercept=False or if\n the X is a sparse matrix, no centering is done, but normalization can still\n be applied. The function returns the statistics necessary to reconstruct\n the input data, which are X_offset, y_offset, X_scale, such that the output\n\n X = (X - X_offset) / X_scale\n\n X_scale is the L2 norm of X - X_offset. If sample_weight is not None,\n then the weighted mean of X and y is zero, and not the mean itself. If\n return_mean=True, the mean, eventually weighted, is returned, independently\n of whether X was centered (option used for optimization with sparse data in\n coordinate_descend).\n\n This is here because nearly all linear models will want their data to be\n centered.\n \"\"\"\n\n if isinstance(sample_weight, numbers.Number):\n sample_weight = None\n\n X = check_array(X, copy=copy, accept_sparse=['csr', 'csc'],\n dtype=FLOAT_DTYPES)\n\n if fit_intercept:\n if sp.issparse(X):\n X_offset, X_var = mean_variance_axis(X, axis=0)\n if not return_mean:\n X_offset = np.zeros(X.shape[1])\n\n if normalize:\n\n # TODO: f_normalize could be used here as well but the function\n # inplace_csr_row_normalize_l2 must be changed such that it\n # can return also the norms computed internally\n\n # transform variance to norm in-place\n X_var *= X.shape[0]\n X_scale = np.sqrt(X_var, X_var)\n del X_var\n X_scale[X_scale == 0] = 1\n inplace_column_scale(X, 1. / X_scale)\n else:\n X_scale = np.ones(X.shape[1])\n\n else:\n X_offset = np.average(X, axis=0, weights=sample_weight)\n X -= X_offset\n if normalize:\n X, X_scale = f_normalize(X, axis=0, copy=False,\n return_norm=True)\n else:\n X_scale = np.ones(X.shape[1])\n y_offset = np.average(y, axis=0, weights=sample_weight)\n y = y - y_offset\n else:\n X_offset = np.zeros(X.shape[1])\n X_scale = np.ones(X.shape[1])\n y_offset = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype)\n\n return X, y, X_offset, y_offset, X_scale\n\n\n# TODO: _rescale_data should be factored into _preprocess_data.\n# Currently, the fact that sag implements its own way to deal with\n# sample_weight makes the refactoring tricky.\n\ndef _rescale_data(X, y, sample_weight):\n \"\"\"Rescale data so as to support sample_weight\"\"\"\n n_samples = X.shape[0]\n sample_weight = sample_weight * np.ones(n_samples)\n sample_weight = np.sqrt(sample_weight)\n sw_matrix = sparse.dia_matrix((sample_weight, 0),\n shape=(n_samples, n_samples))\n X = safe_sparse_dot(sw_matrix, X)\n y = safe_sparse_dot(sw_matrix, y)\n return X, y\n\n\nclass LinearModel(six.with_metaclass(ABCMeta, BaseEstimator)):\n \"\"\"Base class for Linear Models\"\"\"\n\n @abstractmethod\n def fit(self, X, y):\n \"\"\"Fit model.\"\"\"\n\n @deprecated(\" and will be removed in 0.19.\")\n def decision_function(self, X):\n \"\"\"Decision function of the linear model.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = (n_samples, n_features)\n Samples.\n\n Returns\n -------\n C : array, shape = (n_samples,)\n Returns predicted values.\n \"\"\"\n return self._decision_function(X)\n\n def _decision_function(self, X):\n check_is_fitted(self, \"coef_\")\n\n X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])\n return safe_sparse_dot(X, self.coef_.T,\n dense_output=True) + self.intercept_\n\n def predict(self, X):\n \"\"\"Predict using the linear model\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = (n_samples, n_features)\n Samples.\n\n Returns\n -------\n C : array, shape = (n_samples,)\n Returns predicted values.\n \"\"\"\n return self._decision_function(X)\n\n _preprocess_data = staticmethod(_preprocess_data)\n\n def _set_intercept(self, X_offset, y_offset, X_scale):\n \"\"\"Set the intercept_\n \"\"\"\n if self.fit_intercept:\n self.coef_ = self.coef_ / X_scale\n self.intercept_ = y_offset - np.dot(X_offset, self.coef_.T)\n else:\n self.intercept_ = 0.\n\n\n# XXX Should this derive from LinearModel? It should be a mixin, not an ABC.\n# Maybe the n_features checking can be moved to LinearModel.\nclass LinearClassifierMixin(ClassifierMixin):\n \"\"\"Mixin for linear classifiers.\n\n Handles prediction for sparse and dense X.\n \"\"\"\n\n def decision_function(self, X):\n \"\"\"Predict confidence scores for samples.\n\n The confidence score for a sample is the signed distance of that\n sample to the hyperplane.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = (n_samples, n_features)\n Samples.\n\n Returns\n -------\n array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes)\n Confidence scores per (sample, class) combination. In the binary\n case, confidence score for self.classes_[1] where >0 means this\n class would be predicted.\n \"\"\"\n if not hasattr(self, 'coef_') or self.coef_ is None:\n raise NotFittedError(\"This %(name)s instance is not fitted \"\n \"yet\" % {'name': type(self).__name__})\n\n X = check_array(X, accept_sparse='csr')\n\n n_features = self.coef_.shape[1]\n if X.shape[1] != n_features:\n raise ValueError(\"X has %d features per sample; expecting %d\"\n % (X.shape[1], n_features))\n\n scores = safe_sparse_dot(X, self.coef_.T,\n dense_output=True) + self.intercept_\n return scores.ravel() if scores.shape[1] == 1 else scores\n\n def predict(self, X):\n \"\"\"Predict class labels for samples in X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n Samples.\n\n Returns\n -------\n C : array, shape = [n_samples]\n Predicted class label per sample.\n \"\"\"\n scores = self.decision_function(X)\n if len(scores.shape) == 1:\n indices = (scores > 0).astype(np.int)\n else:\n indices = scores.argmax(axis=1)\n return self.classes_[indices]\n\n def _predict_proba_lr(self, X):\n \"\"\"Probability estimation for OvR logistic regression.\n\n Positive class probabilities are computed as\n 1. / (1. + np.exp(-self.decision_function(X)));\n multiclass is handled by normalizing that over all classes.\n \"\"\"\n prob = self.decision_function(X)\n prob *= -1\n np.exp(prob, prob)\n prob += 1\n np.reciprocal(prob, prob)\n if prob.ndim == 1:\n return np.vstack([1 - prob, prob]).T\n else:\n # OvR normalization, like LibLinear's predict_probability\n prob /= prob.sum(axis=1).reshape((prob.shape[0], -1))\n return prob\n\n\nclass SparseCoefMixin(object):\n \"\"\"Mixin for converting coef_ to and from CSR format.\n\n L1-regularizing estimators should inherit this.\n \"\"\"\n\n def densify(self):\n \"\"\"Convert coefficient matrix to dense array format.\n\n Converts the ``coef_`` member (back) to a numpy.ndarray. This is the\n default format of ``coef_`` and is required for fitting, so calling\n this method is only required on models that have previously been\n sparsified; otherwise, it is a no-op.\n\n Returns\n -------\n self: estimator\n \"\"\"\n msg = \"Estimator, %(name)s, must be fitted before densifying.\"\n check_is_fitted(self, \"coef_\", msg=msg)\n if sp.issparse(self.coef_):\n self.coef_ = self.coef_.toarray()\n return self\n\n def sparsify(self):\n \"\"\"Convert coefficient matrix to sparse format.\n\n Converts the ``coef_`` member to a scipy.sparse matrix, which for\n L1-regularized models can be much more memory- and storage-efficient\n than the usual numpy.ndarray representation.\n\n The ``intercept_`` member is not converted.\n\n Notes\n -----\n For non-sparse models, i.e. when there are not many zeros in ``coef_``,\n this may actually *increase* memory usage, so use this method with\n care. A rule of thumb is that the number of zero elements, which can\n be computed with ``(coef_ == 0).sum()``, must be more than 50% for this\n to provide significant benefits.\n\n After calling this method, further fitting with the partial_fit\n method (if any) will not work until you call densify.\n\n Returns\n -------\n self: estimator\n \"\"\"\n msg = \"Estimator, %(name)s, must be fitted before sparsifying.\"\n check_is_fitted(self, \"coef_\", msg=msg)\n self.coef_ = sp.csr_matrix(self.coef_)\n return self\n\n\nclass LinearRegression(LinearModel, RegressorMixin):\n \"\"\"\n Ordinary least squares Linear Regression.\n\n Parameters\n ----------\n fit_intercept : boolean, optional\n whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (e.g. data is expected to be already centered).\n\n normalize : boolean, optional, default False\n If True, the regressors X will be normalized before regression.\n This parameter is ignored when `fit_intercept` is set to False.\n When the regressors are normalized, note that this makes the\n hyperparameters learnt more robust and almost independent of the number\n of samples. The same property is not valid for standardized data.\n However, if you wish to standardize, please use\n `preprocessing.StandardScaler` before calling `fit` on an estimator\n with `normalize=False`.\n\n copy_X : boolean, optional, default True\n If True, X will be copied; else, it may be overwritten.\n\n n_jobs : int, optional, default 1\n The number of jobs to use for the computation.\n If -1 all CPUs are used. This will only provide speedup for\n n_targets > 1 and sufficient large problems.\n\n Attributes\n ----------\n coef_ : array, shape (n_features, ) or (n_targets, n_features)\n Estimated coefficients for the linear regression problem.\n If multiple targets are passed during the fit (y 2D), this\n is a 2D array of shape (n_targets, n_features), while if only\n one target is passed, this is a 1D array of length n_features.\n\n residues_ : array, shape (n_targets,) or (1,) or empty\n Sum of residuals. Squared Euclidean 2-norm for each target passed\n during the fit. If the linear regression problem is under-determined\n (the number of linearly independent rows of the training matrix is less\n than its number of linearly independent columns), this is an empty\n array. If the target vector passed during the fit is 1-dimensional,\n this is a (1,) shape array.\n\n intercept_ : array\n Independent term in the linear model.\n\n Notes\n -----\n From the implementation point of view, this is just plain Ordinary\n Least Squares (scipy.linalg.lstsq) wrapped as a predictor object.\n\n \"\"\"\n\n def __init__(self, fit_intercept=True, normalize=False, copy_X=True,\n n_jobs=1):\n self.fit_intercept = fit_intercept\n self.normalize = normalize\n self.copy_X = copy_X\n self.n_jobs = n_jobs\n\n @property\n @deprecated(\"``residues_`` is deprecated and will be removed in 0.19\")\n def residues_(self):\n \"\"\"Get the residues of the fitted model.\"\"\"\n return self._residues\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"\n Fit linear model.\n\n Parameters\n ----------\n X : numpy array or sparse matrix of shape [n_samples,n_features]\n Training data\n\n y : numpy array of shape [n_samples, n_targets]\n Target values\n\n sample_weight : numpy array of shape [n_samples]\n Individual weights for each sample\n\n .. versionadded:: 0.17\n parameter *sample_weight* support to LinearRegression.\n\n Returns\n -------\n self : returns an instance of self.\n \"\"\"\n\n n_jobs_ = self.n_jobs\n X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],\n y_numeric=True, multi_output=True)\n\n if sample_weight is not None and np.atleast_1d(sample_weight).ndim > 1:\n raise ValueError(\"Sample weights must be 1D array or scalar\")\n\n X, y, X_offset, y_offset, X_scale = self._preprocess_data(\n X, y, fit_intercept=self.fit_intercept, normalize=self.normalize,\n copy=self.copy_X, sample_weight=sample_weight)\n\n if sample_weight is not None:\n # Sample weight can be implemented via a simple rescaling.\n X, y = _rescale_data(X, y, sample_weight)\n\n if sp.issparse(X):\n if y.ndim < 2:\n out = sparse_lsqr(X, y)\n self.coef_ = out[0]\n self._residues = out[3]\n else:\n # sparse_lstsq cannot handle y with shape (M, K)\n outs = Parallel(n_jobs=n_jobs_)(\n delayed(sparse_lsqr)(X, y[:, j].ravel())\n for j in range(y.shape[1]))\n self.coef_ = np.vstack(out[0] for out in outs)\n self._residues = np.vstack(out[3] for out in outs)\n else:\n self.coef_, self._residues, self.rank_, self.singular_ = \\\n linalg.lstsq(X, y)\n self.coef_ = self.coef_.T\n\n if y.ndim == 1:\n self.coef_ = np.ravel(self.coef_)\n self._set_intercept(X_offset, y_offset, X_scale)\n return self\n\n\ndef _pre_fit(X, y, Xy, precompute, normalize, fit_intercept, copy):\n \"\"\"Aux function used at beginning of fit in linear models\"\"\"\n n_samples, n_features = X.shape\n\n if sparse.isspmatrix(X):\n precompute = False\n X, y, X_offset, y_offset, X_scale = _preprocess_data(\n X, y, fit_intercept=fit_intercept, normalize=normalize,\n return_mean=True)\n else:\n # copy was done in fit if necessary\n X, y, X_offset, y_offset, X_scale = _preprocess_data(\n X, y, fit_intercept=fit_intercept, normalize=normalize, copy=copy)\n if hasattr(precompute, '__array__') and (\n fit_intercept and not np.allclose(X_offset, np.zeros(n_features)) or\n normalize and not np.allclose(X_scale, np.ones(n_features))):\n warnings.warn(\"Gram matrix was provided but X was centered\"\n \" to fit intercept, \"\n \"or X was normalized : recomputing Gram matrix.\",\n UserWarning)\n # recompute Gram\n precompute = 'auto'\n Xy = None\n\n # precompute if n_samples > n_features\n if isinstance(precompute, six.string_types) and precompute == 'auto':\n precompute = (n_samples > n_features)\n\n if precompute is True:\n # make sure that the 'precompute' array is contiguous.\n precompute = np.empty(shape=(n_features, n_features), dtype=X.dtype,\n order='C')\n np.dot(X.T, X, out=precompute)\n\n if not hasattr(precompute, '__array__'):\n Xy = None # cannot use Xy if precompute is not Gram\n\n if hasattr(precompute, '__array__') and Xy is None:\n common_dtype = np.find_common_type([X.dtype, y.dtype], [])\n if y.ndim == 1:\n # Xy is 1d, make sure it is contiguous.\n Xy = np.empty(shape=n_features, dtype=common_dtype, order='C')\n np.dot(X.T, y, out=Xy)\n else:\n # Make sure that Xy is always F contiguous even if X or y are not\n # contiguous: the goal is to make it fast to extract the data for a\n # specific target.\n n_targets = y.shape[1]\n Xy = np.empty(shape=(n_features, n_targets), dtype=common_dtype,\n order='F')\n np.dot(y.T, X, out=Xy.T)\n\n return X, y, X_offset, y_offset, X_scale, precompute, Xy\n", "\"\"\"\nRidge regression\n\"\"\"\n\n# Author: Mathieu Blondel <[email protected]>\n# Reuben Fletcher-Costin <[email protected]>\n# Fabian Pedregosa <[email protected]>\n# Michael Eickenberg <[email protected]>\n# License: BSD 3 clause\n\n\nfrom abc import ABCMeta, abstractmethod\nimport warnings\n\nimport numpy as np\nfrom scipy import linalg\nfrom scipy import sparse\nfrom scipy.sparse import linalg as sp_linalg\n\nfrom .base import LinearClassifierMixin, LinearModel, _rescale_data\nfrom .sag import sag_solver\nfrom ..base import RegressorMixin\nfrom ..utils.extmath import safe_sparse_dot\nfrom ..utils.extmath import row_norms\nfrom ..utils import check_X_y\nfrom ..utils import check_array\nfrom ..utils import check_consistent_length\nfrom ..utils import compute_sample_weight\nfrom ..utils import column_or_1d\nfrom ..preprocessing import LabelBinarizer\nfrom ..model_selection import GridSearchCV\nfrom ..externals import six\nfrom ..metrics.scorer import check_scoring\n\n\ndef _solve_sparse_cg(X, y, alpha, max_iter=None, tol=1e-3, verbose=0):\n n_samples, n_features = X.shape\n X1 = sp_linalg.aslinearoperator(X)\n coefs = np.empty((y.shape[1], n_features))\n\n if n_features > n_samples:\n def create_mv(curr_alpha):\n def _mv(x):\n return X1.matvec(X1.rmatvec(x)) + curr_alpha * x\n return _mv\n else:\n def create_mv(curr_alpha):\n def _mv(x):\n return X1.rmatvec(X1.matvec(x)) + curr_alpha * x\n return _mv\n\n for i in range(y.shape[1]):\n y_column = y[:, i]\n\n mv = create_mv(alpha[i])\n if n_features > n_samples:\n # kernel ridge\n # w = X.T * inv(X X^t + alpha*Id) y\n C = sp_linalg.LinearOperator(\n (n_samples, n_samples), matvec=mv, dtype=X.dtype)\n coef, info = sp_linalg.cg(C, y_column, tol=tol)\n coefs[i] = X1.rmatvec(coef)\n else:\n # linear ridge\n # w = inv(X^t X + alpha*Id) * X.T y\n y_column = X1.rmatvec(y_column)\n C = sp_linalg.LinearOperator(\n (n_features, n_features), matvec=mv, dtype=X.dtype)\n coefs[i], info = sp_linalg.cg(C, y_column, maxiter=max_iter,\n tol=tol)\n if info < 0:\n raise ValueError(\"Failed with error code %d\" % info)\n\n if max_iter is None and info > 0 and verbose:\n warnings.warn(\"sparse_cg did not converge after %d iterations.\" %\n info)\n\n return coefs\n\n\ndef _solve_lsqr(X, y, alpha, max_iter=None, tol=1e-3):\n n_samples, n_features = X.shape\n coefs = np.empty((y.shape[1], n_features))\n n_iter = np.empty(y.shape[1], dtype=np.int32)\n\n # According to the lsqr documentation, alpha = damp^2.\n sqrt_alpha = np.sqrt(alpha)\n\n for i in range(y.shape[1]):\n y_column = y[:, i]\n info = sp_linalg.lsqr(X, y_column, damp=sqrt_alpha[i],\n atol=tol, btol=tol, iter_lim=max_iter)\n coefs[i] = info[0]\n n_iter[i] = info[2]\n\n return coefs, n_iter\n\n\ndef _solve_cholesky(X, y, alpha):\n # w = inv(X^t X + alpha*Id) * X.T y\n n_samples, n_features = X.shape\n n_targets = y.shape[1]\n\n A = safe_sparse_dot(X.T, X, dense_output=True)\n Xy = safe_sparse_dot(X.T, y, dense_output=True)\n\n one_alpha = np.array_equal(alpha, len(alpha) * [alpha[0]])\n\n if one_alpha:\n A.flat[::n_features + 1] += alpha[0]\n return linalg.solve(A, Xy, sym_pos=True,\n overwrite_a=True).T\n else:\n coefs = np.empty([n_targets, n_features])\n for coef, target, current_alpha in zip(coefs, Xy.T, alpha):\n A.flat[::n_features + 1] += current_alpha\n coef[:] = linalg.solve(A, target, sym_pos=True,\n overwrite_a=False).ravel()\n A.flat[::n_features + 1] -= current_alpha\n return coefs\n\n\ndef _solve_cholesky_kernel(K, y, alpha, sample_weight=None, copy=False):\n # dual_coef = inv(X X^t + alpha*Id) y\n n_samples = K.shape[0]\n n_targets = y.shape[1]\n\n if copy:\n K = K.copy()\n\n alpha = np.atleast_1d(alpha)\n one_alpha = (alpha == alpha[0]).all()\n has_sw = isinstance(sample_weight, np.ndarray) \\\n or sample_weight not in [1.0, None]\n\n if has_sw:\n # Unlike other solvers, we need to support sample_weight directly\n # because K might be a pre-computed kernel.\n sw = np.sqrt(np.atleast_1d(sample_weight))\n y = y * sw[:, np.newaxis]\n K *= np.outer(sw, sw)\n\n if one_alpha:\n # Only one penalty, we can solve multi-target problems in one time.\n K.flat[::n_samples + 1] += alpha[0]\n\n try:\n # Note: we must use overwrite_a=False in order to be able to\n # use the fall-back solution below in case a LinAlgError\n # is raised\n dual_coef = linalg.solve(K, y, sym_pos=True,\n overwrite_a=False)\n except np.linalg.LinAlgError:\n warnings.warn(\"Singular matrix in solving dual problem. Using \"\n \"least-squares solution instead.\")\n dual_coef = linalg.lstsq(K, y)[0]\n\n # K is expensive to compute and store in memory so change it back in\n # case it was user-given.\n K.flat[::n_samples + 1] -= alpha[0]\n\n if has_sw:\n dual_coef *= sw[:, np.newaxis]\n\n return dual_coef\n else:\n # One penalty per target. We need to solve each target separately.\n dual_coefs = np.empty([n_targets, n_samples])\n\n for dual_coef, target, current_alpha in zip(dual_coefs, y.T, alpha):\n K.flat[::n_samples + 1] += current_alpha\n\n dual_coef[:] = linalg.solve(K, target, sym_pos=True,\n overwrite_a=False).ravel()\n\n K.flat[::n_samples + 1] -= current_alpha\n\n if has_sw:\n dual_coefs *= sw[np.newaxis, :]\n\n return dual_coefs.T\n\n\ndef _solve_svd(X, y, alpha):\n U, s, Vt = linalg.svd(X, full_matrices=False)\n idx = s > 1e-15 # same default value as scipy.linalg.pinv\n s_nnz = s[idx][:, np.newaxis]\n UTy = np.dot(U.T, y)\n d = np.zeros((s.size, alpha.size))\n d[idx] = s_nnz / (s_nnz ** 2 + alpha)\n d_UT_y = d * UTy\n return np.dot(Vt.T, d_UT_y).T\n\n\ndef ridge_regression(X, y, alpha, sample_weight=None, solver='auto',\n max_iter=None, tol=1e-3, verbose=0, random_state=None,\n return_n_iter=False, return_intercept=False):\n \"\"\"Solve the ridge equation by the method of normal equations.\n\n Read more in the :ref:`User Guide <ridge_regression>`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, LinearOperator},\n shape = [n_samples, n_features]\n Training data\n\n y : array-like, shape = [n_samples] or [n_samples, n_targets]\n Target values\n\n alpha : {float, array-like},\n shape = [n_targets] if array-like\n Regularization strength; must be a positive float. Regularization\n improves the conditioning of the problem and reduces the variance of\n the estimates. Larger values specify stronger regularization.\n Alpha corresponds to ``C^-1`` in other linear models such as \n LogisticRegression or LinearSVC. If an array is passed, penalties are\n assumed to be specific to the targets. Hence they must correspond in\n number.\n\n max_iter : int, optional\n Maximum number of iterations for conjugate gradient solver.\n For 'sparse_cg' and 'lsqr' solvers, the default value is determined\n by scipy.sparse.linalg. For 'sag' solver, the default value is 1000.\n\n sample_weight : float or numpy array of shape [n_samples]\n Individual weights for each sample. If sample_weight is not None and\n solver='auto', the solver will be set to 'cholesky'.\n\n .. versionadded:: 0.17\n\n solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg'}\n Solver to use in the computational routines:\n\n - 'auto' chooses the solver automatically based on the type of data.\n\n - 'svd' uses a Singular Value Decomposition of X to compute the Ridge\n coefficients. More stable for singular matrices than\n 'cholesky'.\n\n - 'cholesky' uses the standard scipy.linalg.solve function to\n obtain a closed-form solution via a Cholesky decomposition of\n dot(X.T, X)\n\n - 'sparse_cg' uses the conjugate gradient solver as found in\n scipy.sparse.linalg.cg. As an iterative algorithm, this solver is\n more appropriate than 'cholesky' for large-scale data\n (possibility to set `tol` and `max_iter`).\n\n - 'lsqr' uses the dedicated regularized least-squares routine\n scipy.sparse.linalg.lsqr. It is the fastest but may not be available\n in old scipy versions. It also uses an iterative procedure.\n\n - 'sag' uses a Stochastic Average Gradient descent. It also uses an\n iterative procedure, and is often faster than other solvers when\n both n_samples and n_features are large. Note that 'sag' fast\n convergence is only guaranteed on features with approximately the\n same scale. You can preprocess the data with a scaler from\n sklearn.preprocessing.\n\n All last four solvers support both dense and sparse data. However,\n only 'sag' supports sparse input when `fit_intercept` is True.\n\n .. versionadded:: 0.17\n Stochastic Average Gradient descent solver.\n\n tol : float\n Precision of the solution.\n\n verbose : int\n Verbosity level. Setting verbose > 0 will display additional\n information depending on the solver used.\n\n random_state : int seed, RandomState instance, or None (default)\n The seed of the pseudo random number generator to use when\n shuffling the data. Used only in 'sag' solver.\n\n return_n_iter : boolean, default False\n If True, the method also returns `n_iter`, the actual number of\n iteration performed by the solver.\n\n .. versionadded:: 0.17\n\n return_intercept : boolean, default False\n If True and if X is sparse, the method also returns the intercept,\n and the solver is automatically changed to 'sag'. This is only a\n temporary fix for fitting the intercept with sparse data. For dense\n data, use sklearn.linear_model._preprocess_data before your regression.\n\n .. versionadded:: 0.17\n\n Returns\n -------\n coef : array, shape = [n_features] or [n_targets, n_features]\n Weight vector(s).\n\n n_iter : int, optional\n The actual number of iteration performed by the solver.\n Only returned if `return_n_iter` is True.\n\n intercept : float or array, shape = [n_targets]\n The intercept of the model. Only returned if `return_intercept`\n is True and if X is a scipy sparse array.\n\n Notes\n -----\n This function won't compute the intercept.\n \"\"\"\n if return_intercept and sparse.issparse(X) and solver != 'sag':\n if solver != 'auto':\n warnings.warn(\"In Ridge, only 'sag' solver can currently fit the \"\n \"intercept when X is sparse. Solver has been \"\n \"automatically changed into 'sag'.\")\n solver = 'sag'\n\n # SAG needs X and y columns to be C-contiguous and np.float64\n if solver == 'sag':\n X = check_array(X, accept_sparse=['csr'],\n dtype=np.float64, order='C')\n y = check_array(y, dtype=np.float64, ensure_2d=False, order='F')\n else:\n X = check_array(X, accept_sparse=['csr', 'csc', 'coo'],\n dtype=np.float64)\n y = check_array(y, dtype='numeric', ensure_2d=False)\n check_consistent_length(X, y)\n\n n_samples, n_features = X.shape\n\n if y.ndim > 2:\n raise ValueError(\"Target y has the wrong shape %s\" % str(y.shape))\n\n ravel = False\n if y.ndim == 1:\n y = y.reshape(-1, 1)\n ravel = True\n\n n_samples_, n_targets = y.shape\n\n if n_samples != n_samples_:\n raise ValueError(\"Number of samples in X and y does not correspond:\"\n \" %d != %d\" % (n_samples, n_samples_))\n\n has_sw = sample_weight is not None\n\n if solver == 'auto':\n # cholesky if it's a dense array and cg in any other case\n if not sparse.issparse(X) or has_sw:\n solver = 'cholesky'\n else:\n solver = 'sparse_cg'\n\n elif solver == 'lsqr' and not hasattr(sp_linalg, 'lsqr'):\n warnings.warn(\"\"\"lsqr not available on this machine, falling back\n to sparse_cg.\"\"\")\n solver = 'sparse_cg'\n\n if has_sw:\n if np.atleast_1d(sample_weight).ndim > 1:\n raise ValueError(\"Sample weights must be 1D array or scalar\")\n\n if solver != 'sag':\n # SAG supports sample_weight directly. For other solvers,\n # we implement sample_weight via a simple rescaling.\n X, y = _rescale_data(X, y, sample_weight)\n\n # There should be either 1 or n_targets penalties\n alpha = np.asarray(alpha).ravel()\n if alpha.size not in [1, n_targets]:\n raise ValueError(\"Number of targets and number of penalties \"\n \"do not correspond: %d != %d\"\n % (alpha.size, n_targets))\n\n if alpha.size == 1 and n_targets > 1:\n alpha = np.repeat(alpha, n_targets)\n\n if solver not in ('sparse_cg', 'cholesky', 'svd', 'lsqr', 'sag'):\n raise ValueError('Solver %s not understood' % solver)\n\n n_iter = None\n if solver == 'sparse_cg':\n coef = _solve_sparse_cg(X, y, alpha, max_iter, tol, verbose)\n\n elif solver == 'lsqr':\n coef, n_iter = _solve_lsqr(X, y, alpha, max_iter, tol)\n\n elif solver == 'cholesky':\n if n_features > n_samples:\n K = safe_sparse_dot(X, X.T, dense_output=True)\n try:\n dual_coef = _solve_cholesky_kernel(K, y, alpha)\n\n coef = safe_sparse_dot(X.T, dual_coef, dense_output=True).T\n except linalg.LinAlgError:\n # use SVD solver if matrix is singular\n solver = 'svd'\n\n else:\n try:\n coef = _solve_cholesky(X, y, alpha)\n except linalg.LinAlgError:\n # use SVD solver if matrix is singular\n solver = 'svd'\n\n elif solver == 'sag':\n # precompute max_squared_sum for all targets\n max_squared_sum = row_norms(X, squared=True).max()\n\n coef = np.empty((y.shape[1], n_features))\n n_iter = np.empty(y.shape[1], dtype=np.int32)\n intercept = np.zeros((y.shape[1], ))\n for i, (alpha_i, target) in enumerate(zip(alpha, y.T)):\n init = {'coef': np.zeros((n_features + int(return_intercept), 1))}\n coef_, n_iter_, _ = sag_solver(\n X, target.ravel(), sample_weight, 'squared', alpha_i,\n max_iter, tol, verbose, random_state, False, max_squared_sum,\n init)\n if return_intercept:\n coef[i] = coef_[:-1]\n intercept[i] = coef_[-1]\n else:\n coef[i] = coef_\n n_iter[i] = n_iter_\n\n if intercept.shape[0] == 1:\n intercept = intercept[0]\n coef = np.asarray(coef)\n\n if solver == 'svd':\n if sparse.issparse(X):\n raise TypeError('SVD solver does not support sparse'\n ' inputs currently')\n coef = _solve_svd(X, y, alpha)\n\n if ravel:\n # When y was passed as a 1d-array, we flatten the coefficients.\n coef = coef.ravel()\n\n if return_n_iter and return_intercept:\n return coef, n_iter, intercept\n elif return_intercept:\n return coef, intercept\n elif return_n_iter:\n return coef, n_iter\n else:\n return coef\n\n\nclass _BaseRidge(six.with_metaclass(ABCMeta, LinearModel)):\n\n @abstractmethod\n def __init__(self, alpha=1.0, fit_intercept=True, normalize=False,\n copy_X=True, max_iter=None, tol=1e-3, solver=\"auto\",\n random_state=None):\n self.alpha = alpha\n self.fit_intercept = fit_intercept\n self.normalize = normalize\n self.copy_X = copy_X\n self.max_iter = max_iter\n self.tol = tol\n self.solver = solver\n self.random_state = random_state\n\n def fit(self, X, y, sample_weight=None):\n X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], dtype=np.float64,\n multi_output=True, y_numeric=True)\n\n if ((sample_weight is not None) and\n np.atleast_1d(sample_weight).ndim > 1):\n raise ValueError(\"Sample weights must be 1D array or scalar\")\n\n X, y, X_offset, y_offset, X_scale = self._preprocess_data(\n X, y, self.fit_intercept, self.normalize, self.copy_X,\n sample_weight=sample_weight)\n\n # temporary fix for fitting the intercept with sparse data using 'sag'\n if sparse.issparse(X) and self.fit_intercept:\n self.coef_, self.n_iter_, self.intercept_ = ridge_regression(\n X, y, alpha=self.alpha, sample_weight=sample_weight,\n max_iter=self.max_iter, tol=self.tol, solver=self.solver,\n random_state=self.random_state, return_n_iter=True,\n return_intercept=True)\n self.intercept_ += y_offset\n else:\n self.coef_, self.n_iter_ = ridge_regression(\n X, y, alpha=self.alpha, sample_weight=sample_weight,\n max_iter=self.max_iter, tol=self.tol, solver=self.solver,\n random_state=self.random_state, return_n_iter=True,\n return_intercept=False)\n self._set_intercept(X_offset, y_offset, X_scale)\n\n return self\n\n\nclass Ridge(_BaseRidge, RegressorMixin):\n \"\"\"Linear least squares with l2 regularization.\n\n This model solves a regression model where the loss function is\n the linear least squares function and regularization is given by\n the l2-norm. Also known as Ridge Regression or Tikhonov regularization.\n This estimator has built-in support for multi-variate regression\n (i.e., when y is a 2d-array of shape [n_samples, n_targets]).\n\n Read more in the :ref:`User Guide <ridge_regression>`.\n\n Parameters\n ----------\n alpha : {float, array-like}, shape (n_targets)\n Regularization strength; must be a positive float. Regularization\n improves the conditioning of the problem and reduces the variance of\n the estimates. Larger values specify stronger regularization.\n Alpha corresponds to ``C^-1`` in other linear models such as \n LogisticRegression or LinearSVC. If an array is passed, penalties are\n assumed to be specific to the targets. Hence they must correspond in\n number.\n\n copy_X : boolean, optional, default True\n If True, X will be copied; else, it may be overwritten.\n\n fit_intercept : boolean\n Whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (e.g. data is expected to be already centered).\n\n max_iter : int, optional\n Maximum number of iterations for conjugate gradient solver.\n For 'sparse_cg' and 'lsqr' solvers, the default value is determined\n by scipy.sparse.linalg. For 'sag' solver, the default value is 1000.\n\n normalize : boolean, optional, default False\n If True, the regressors X will be normalized before regression.\n This parameter is ignored when `fit_intercept` is set to False.\n When the regressors are normalized, note that this makes the\n hyperparameters learnt more robust and almost independent of the number\n of samples. The same property is not valid for standardized data.\n However, if you wish to standardize, please use\n `preprocessing.StandardScaler` before calling `fit` on an estimator\n with `normalize=False`.\n\n solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag'}\n Solver to use in the computational routines:\n\n - 'auto' chooses the solver automatically based on the type of data.\n\n - 'svd' uses a Singular Value Decomposition of X to compute the Ridge\n coefficients. More stable for singular matrices than\n 'cholesky'.\n\n - 'cholesky' uses the standard scipy.linalg.solve function to\n obtain a closed-form solution.\n\n - 'sparse_cg' uses the conjugate gradient solver as found in\n scipy.sparse.linalg.cg. As an iterative algorithm, this solver is\n more appropriate than 'cholesky' for large-scale data\n (possibility to set `tol` and `max_iter`).\n\n - 'lsqr' uses the dedicated regularized least-squares routine\n scipy.sparse.linalg.lsqr. It is the fastest but may not be available\n in old scipy versions. It also uses an iterative procedure.\n\n - 'sag' uses a Stochastic Average Gradient descent. It also uses an\n iterative procedure, and is often faster than other solvers when\n both n_samples and n_features are large. Note that 'sag' fast\n convergence is only guaranteed on features with approximately the\n same scale. You can preprocess the data with a scaler from\n sklearn.preprocessing.\n\n All last four solvers support both dense and sparse data. However,\n only 'sag' supports sparse input when `fit_intercept` is True.\n\n .. versionadded:: 0.17\n Stochastic Average Gradient descent solver.\n\n tol : float\n Precision of the solution.\n\n random_state : int seed, RandomState instance, or None (default)\n The seed of the pseudo random number generator to use when\n shuffling the data. Used only in 'sag' solver.\n\n .. versionadded:: 0.17\n *random_state* to support Stochastic Average Gradient.\n\n Attributes\n ----------\n coef_ : array, shape (n_features,) or (n_targets, n_features)\n Weight vector(s).\n\n intercept_ : float | array, shape = (n_targets,)\n Independent term in decision function. Set to 0.0 if\n ``fit_intercept = False``.\n\n n_iter_ : array or None, shape (n_targets,)\n Actual number of iterations for each target. Available only for\n sag and lsqr solvers. Other solvers will return None.\n\n .. versionadded:: 0.17\n\n See also\n --------\n RidgeClassifier, RidgeCV, :class:`sklearn.kernel_ridge.KernelRidge`\n\n Examples\n --------\n >>> from sklearn.linear_model import Ridge\n >>> import numpy as np\n >>> n_samples, n_features = 10, 5\n >>> np.random.seed(0)\n >>> y = np.random.randn(n_samples)\n >>> X = np.random.randn(n_samples, n_features)\n >>> clf = Ridge(alpha=1.0)\n >>> clf.fit(X, y) # doctest: +NORMALIZE_WHITESPACE\n Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,\n normalize=False, random_state=None, solver='auto', tol=0.001)\n\n \"\"\"\n def __init__(self, alpha=1.0, fit_intercept=True, normalize=False,\n copy_X=True, max_iter=None, tol=1e-3, solver=\"auto\",\n random_state=None):\n super(Ridge, self).__init__(alpha=alpha, fit_intercept=fit_intercept,\n normalize=normalize, copy_X=copy_X,\n max_iter=max_iter, tol=tol, solver=solver,\n random_state=random_state)\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit Ridge regression model\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n Training data\n\n y : array-like, shape = [n_samples] or [n_samples, n_targets]\n Target values\n\n sample_weight : float or numpy array of shape [n_samples]\n Individual weights for each sample\n\n Returns\n -------\n self : returns an instance of self.\n \"\"\"\n return super(Ridge, self).fit(X, y, sample_weight=sample_weight)\n\n\nclass RidgeClassifier(LinearClassifierMixin, _BaseRidge):\n \"\"\"Classifier using Ridge regression.\n\n Read more in the :ref:`User Guide <ridge_regression>`.\n\n Parameters\n ----------\n alpha : float\n Regularization strength; must be a positive float. Regularization\n improves the conditioning of the problem and reduces the variance of\n the estimates. Larger values specify stronger regularization.\n Alpha corresponds to ``C^-1`` in other linear models such as \n LogisticRegression or LinearSVC.\n\n class_weight : dict or 'balanced', optional\n Weights associated with classes in the form ``{class_label: weight}``.\n If not given, all classes are supposed to have weight one.\n\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``\n\n copy_X : boolean, optional, default True\n If True, X will be copied; else, it may be overwritten.\n\n fit_intercept : boolean\n Whether to calculate the intercept for this model. If set to false, no\n intercept will be used in calculations (e.g. data is expected to be\n already centered).\n\n max_iter : int, optional\n Maximum number of iterations for conjugate gradient solver.\n The default value is determined by scipy.sparse.linalg.\n\n normalize : boolean, optional, default False\n If True, the regressors X will be normalized before regression.\n This parameter is ignored when `fit_intercept` is set to False.\n When the regressors are normalized, note that this makes the\n hyperparameters learnt more robust and almost independent of the number\n of samples. The same property is not valid for standardized data.\n However, if you wish to standardize, please use\n `preprocessing.StandardScaler` before calling `fit` on an estimator\n with `normalize=False`.\n\n solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag'}\n Solver to use in the computational routines:\n\n - 'auto' chooses the solver automatically based on the type of data.\n\n - 'svd' uses a Singular Value Decomposition of X to compute the Ridge\n coefficients. More stable for singular matrices than\n 'cholesky'.\n\n - 'cholesky' uses the standard scipy.linalg.solve function to\n obtain a closed-form solution.\n\n - 'sparse_cg' uses the conjugate gradient solver as found in\n scipy.sparse.linalg.cg. As an iterative algorithm, this solver is\n more appropriate than 'cholesky' for large-scale data\n (possibility to set `tol` and `max_iter`).\n\n - 'lsqr' uses the dedicated regularized least-squares routine\n scipy.sparse.linalg.lsqr. It is the fastest but may not be available\n in old scipy versions. It also uses an iterative procedure.\n\n - 'sag' uses a Stochastic Average Gradient descent. It also uses an\n iterative procedure, and is faster than other solvers when both\n n_samples and n_features are large.\n\n .. versionadded:: 0.17\n Stochastic Average Gradient descent solver.\n\n tol : float\n Precision of the solution.\n\n random_state : int seed, RandomState instance, or None (default)\n The seed of the pseudo random number generator to use when\n shuffling the data. Used in 'sag' solver.\n\n Attributes\n ----------\n coef_ : array, shape (n_features,) or (n_classes, n_features)\n Weight vector(s).\n\n intercept_ : float | array, shape = (n_targets,)\n Independent term in decision function. Set to 0.0 if\n ``fit_intercept = False``.\n\n n_iter_ : array or None, shape (n_targets,)\n Actual number of iterations for each target. Available only for\n sag and lsqr solvers. Other solvers will return None.\n\n See also\n --------\n Ridge, RidgeClassifierCV\n\n Notes\n -----\n For multi-class classification, n_class classifiers are trained in\n a one-versus-all approach. Concretely, this is implemented by taking\n advantage of the multi-variate response support in Ridge.\n \"\"\"\n def __init__(self, alpha=1.0, fit_intercept=True, normalize=False,\n copy_X=True, max_iter=None, tol=1e-3, class_weight=None,\n solver=\"auto\", random_state=None):\n super(RidgeClassifier, self).__init__(\n alpha=alpha, fit_intercept=fit_intercept, normalize=normalize,\n copy_X=copy_X, max_iter=max_iter, tol=tol, solver=solver,\n random_state=random_state)\n self.class_weight = class_weight\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit Ridge regression model.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples,n_features]\n Training data\n\n y : array-like, shape = [n_samples]\n Target values\n\n sample_weight : float or numpy array of shape (n_samples,)\n Sample weight.\n\n .. versionadded:: 0.17\n *sample_weight* support to Classifier.\n\n Returns\n -------\n self : returns an instance of self.\n \"\"\"\n self._label_binarizer = LabelBinarizer(pos_label=1, neg_label=-1)\n Y = self._label_binarizer.fit_transform(y)\n if not self._label_binarizer.y_type_.startswith('multilabel'):\n y = column_or_1d(y, warn=True)\n else:\n # we don't (yet) support multi-label classification in Ridge\n raise ValueError(\n \"%s doesn't support multi-label classification\" % (\n self.__class__.__name__))\n\n if self.class_weight:\n if sample_weight is None:\n sample_weight = 1.\n # modify the sample weights with the corresponding class weight\n sample_weight = (sample_weight *\n compute_sample_weight(self.class_weight, y))\n\n super(RidgeClassifier, self).fit(X, Y, sample_weight=sample_weight)\n return self\n\n @property\n def classes_(self):\n return self._label_binarizer.classes_\n\n\nclass _RidgeGCV(LinearModel):\n \"\"\"Ridge regression with built-in Generalized Cross-Validation\n\n It allows efficient Leave-One-Out cross-validation.\n\n This class is not intended to be used directly. Use RidgeCV instead.\n\n Notes\n -----\n\n We want to solve (K + alpha*Id)c = y,\n where K = X X^T is the kernel matrix.\n\n Let G = (K + alpha*Id)^-1.\n\n Dual solution: c = Gy\n Primal solution: w = X^T c\n\n Compute eigendecomposition K = Q V Q^T.\n Then G = Q (V + alpha*Id)^-1 Q^T,\n where (V + alpha*Id) is diagonal.\n It is thus inexpensive to inverse for many alphas.\n\n Let loov be the vector of prediction values for each example\n when the model was fitted with all examples but this example.\n\n loov = (KGY - diag(KG)Y) / diag(I-KG)\n\n Let looe be the vector of prediction errors for each example\n when the model was fitted with all examples but this example.\n\n looe = y - loov = c / diag(G)\n\n References\n ----------\n http://cbcl.mit.edu/projects/cbcl/publications/ps/MIT-CSAIL-TR-2007-025.pdf\n http://www.mit.edu/~9.520/spring07/Classes/rlsslides.pdf\n \"\"\"\n\n def __init__(self, alphas=(0.1, 1.0, 10.0),\n fit_intercept=True, normalize=False,\n scoring=None, copy_X=True,\n gcv_mode=None, store_cv_values=False):\n self.alphas = np.asarray(alphas)\n self.fit_intercept = fit_intercept\n self.normalize = normalize\n self.scoring = scoring\n self.copy_X = copy_X\n self.gcv_mode = gcv_mode\n self.store_cv_values = store_cv_values\n\n def _pre_compute(self, X, y):\n # even if X is very sparse, K is usually very dense\n K = safe_sparse_dot(X, X.T, dense_output=True)\n v, Q = linalg.eigh(K)\n QT_y = np.dot(Q.T, y)\n return v, Q, QT_y\n\n def _decomp_diag(self, v_prime, Q):\n # compute diagonal of the matrix: dot(Q, dot(diag(v_prime), Q^T))\n return (v_prime * Q ** 2).sum(axis=-1)\n\n def _diag_dot(self, D, B):\n # compute dot(diag(D), B)\n if len(B.shape) > 1:\n # handle case where B is > 1-d\n D = D[(slice(None), ) + (np.newaxis, ) * (len(B.shape) - 1)]\n return D * B\n\n def _errors_and_values_helper(self, alpha, y, v, Q, QT_y):\n \"\"\"Helper function to avoid code duplication between self._errors and\n self._values.\n\n Notes\n -----\n We don't construct matrix G, instead compute action on y & diagonal.\n \"\"\"\n w = 1.0 / (v + alpha)\n c = np.dot(Q, self._diag_dot(w, QT_y))\n G_diag = self._decomp_diag(w, Q)\n # handle case where y is 2-d\n if len(y.shape) != 1:\n G_diag = G_diag[:, np.newaxis]\n return G_diag, c\n\n def _errors(self, alpha, y, v, Q, QT_y):\n G_diag, c = self._errors_and_values_helper(alpha, y, v, Q, QT_y)\n return (c / G_diag) ** 2, c\n\n def _values(self, alpha, y, v, Q, QT_y):\n G_diag, c = self._errors_and_values_helper(alpha, y, v, Q, QT_y)\n return y - (c / G_diag), c\n\n def _pre_compute_svd(self, X, y):\n if sparse.issparse(X):\n raise TypeError(\"SVD not supported for sparse matrices\")\n U, s, _ = linalg.svd(X, full_matrices=0)\n v = s ** 2\n UT_y = np.dot(U.T, y)\n return v, U, UT_y\n\n def _errors_and_values_svd_helper(self, alpha, y, v, U, UT_y):\n \"\"\"Helper function to avoid code duplication between self._errors_svd\n and self._values_svd.\n \"\"\"\n w = ((v + alpha) ** -1) - (alpha ** -1)\n c = np.dot(U, self._diag_dot(w, UT_y)) + (alpha ** -1) * y\n G_diag = self._decomp_diag(w, U) + (alpha ** -1)\n if len(y.shape) != 1:\n # handle case where y is 2-d\n G_diag = G_diag[:, np.newaxis]\n return G_diag, c\n\n def _errors_svd(self, alpha, y, v, U, UT_y):\n G_diag, c = self._errors_and_values_svd_helper(alpha, y, v, U, UT_y)\n return (c / G_diag) ** 2, c\n\n def _values_svd(self, alpha, y, v, U, UT_y):\n G_diag, c = self._errors_and_values_svd_helper(alpha, y, v, U, UT_y)\n return y - (c / G_diag), c\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit Ridge regression model\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n Training data\n\n y : array-like, shape = [n_samples] or [n_samples, n_targets]\n Target values\n\n sample_weight : float or array-like of shape [n_samples]\n Sample weight\n\n Returns\n -------\n self : Returns self.\n \"\"\"\n X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], dtype=np.float64,\n multi_output=True, y_numeric=True)\n\n n_samples, n_features = X.shape\n\n X, y, X_offset, y_offset, X_scale = LinearModel._preprocess_data(\n X, y, self.fit_intercept, self.normalize, self.copy_X,\n sample_weight=sample_weight)\n\n gcv_mode = self.gcv_mode\n with_sw = len(np.shape(sample_weight))\n\n if gcv_mode is None or gcv_mode == 'auto':\n if sparse.issparse(X) or n_features > n_samples or with_sw:\n gcv_mode = 'eigen'\n else:\n gcv_mode = 'svd'\n elif gcv_mode == \"svd\" and with_sw:\n # FIXME non-uniform sample weights not yet supported\n warnings.warn(\"non-uniform sample weights unsupported for svd, \"\n \"forcing usage of eigen\")\n gcv_mode = 'eigen'\n\n if gcv_mode == 'eigen':\n _pre_compute = self._pre_compute\n _errors = self._errors\n _values = self._values\n elif gcv_mode == 'svd':\n # assert n_samples >= n_features\n _pre_compute = self._pre_compute_svd\n _errors = self._errors_svd\n _values = self._values_svd\n else:\n raise ValueError('bad gcv_mode \"%s\"' % gcv_mode)\n\n v, Q, QT_y = _pre_compute(X, y)\n n_y = 1 if len(y.shape) == 1 else y.shape[1]\n cv_values = np.zeros((n_samples * n_y, len(self.alphas)))\n C = []\n\n scorer = check_scoring(self, scoring=self.scoring, allow_none=True)\n error = scorer is None\n\n for i, alpha in enumerate(self.alphas):\n weighted_alpha = (sample_weight * alpha\n if sample_weight is not None\n else alpha)\n if error:\n out, c = _errors(weighted_alpha, y, v, Q, QT_y)\n else:\n out, c = _values(weighted_alpha, y, v, Q, QT_y)\n cv_values[:, i] = out.ravel()\n C.append(c)\n\n if error:\n best = cv_values.mean(axis=0).argmin()\n else:\n # The scorer want an object that will make the predictions but\n # they are already computed efficiently by _RidgeGCV. This\n # identity_estimator will just return them\n def identity_estimator():\n pass\n identity_estimator.decision_function = lambda y_predict: y_predict\n identity_estimator.predict = lambda y_predict: y_predict\n\n out = [scorer(identity_estimator, y.ravel(), cv_values[:, i])\n for i in range(len(self.alphas))]\n best = np.argmax(out)\n\n self.alpha_ = self.alphas[best]\n self.dual_coef_ = C[best]\n self.coef_ = safe_sparse_dot(self.dual_coef_.T, X)\n\n self._set_intercept(X_offset, y_offset, X_scale)\n\n if self.store_cv_values:\n if len(y.shape) == 1:\n cv_values_shape = n_samples, len(self.alphas)\n else:\n cv_values_shape = n_samples, n_y, len(self.alphas)\n self.cv_values_ = cv_values.reshape(cv_values_shape)\n\n return self\n\n\nclass _BaseRidgeCV(LinearModel):\n def __init__(self, alphas=(0.1, 1.0, 10.0),\n fit_intercept=True, normalize=False, scoring=None,\n cv=None, gcv_mode=None,\n store_cv_values=False):\n self.alphas = alphas\n self.fit_intercept = fit_intercept\n self.normalize = normalize\n self.scoring = scoring\n self.cv = cv\n self.gcv_mode = gcv_mode\n self.store_cv_values = store_cv_values\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit Ridge regression model\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Training data\n\n y : array-like, shape = [n_samples] or [n_samples, n_targets]\n Target values\n\n sample_weight : float or array-like of shape [n_samples]\n Sample weight\n\n Returns\n -------\n self : Returns self.\n \"\"\"\n if self.cv is None:\n estimator = _RidgeGCV(self.alphas,\n fit_intercept=self.fit_intercept,\n normalize=self.normalize,\n scoring=self.scoring,\n gcv_mode=self.gcv_mode,\n store_cv_values=self.store_cv_values)\n estimator.fit(X, y, sample_weight=sample_weight)\n self.alpha_ = estimator.alpha_\n if self.store_cv_values:\n self.cv_values_ = estimator.cv_values_\n else:\n if self.store_cv_values:\n raise ValueError(\"cv!=None and store_cv_values=True \"\n \" are incompatible\")\n parameters = {'alpha': self.alphas}\n fit_params = {'sample_weight': sample_weight}\n gs = GridSearchCV(Ridge(fit_intercept=self.fit_intercept),\n parameters, fit_params=fit_params, cv=self.cv)\n gs.fit(X, y)\n estimator = gs.best_estimator_\n self.alpha_ = gs.best_estimator_.alpha\n\n self.coef_ = estimator.coef_\n self.intercept_ = estimator.intercept_\n\n return self\n\n\nclass RidgeCV(_BaseRidgeCV, RegressorMixin):\n \"\"\"Ridge regression with built-in cross-validation.\n\n By default, it performs Generalized Cross-Validation, which is a form of\n efficient Leave-One-Out cross-validation.\n\n Read more in the :ref:`User Guide <ridge_regression>`.\n\n Parameters\n ----------\n alphas : numpy array of shape [n_alphas]\n Array of alpha values to try.\n Regularization strength; must be a positive float. Regularization\n improves the conditioning of the problem and reduces the variance of\n the estimates. Larger values specify stronger regularization.\n Alpha corresponds to ``C^-1`` in other linear models such as \n LogisticRegression or LinearSVC. \n\n fit_intercept : boolean\n Whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (e.g. data is expected to be already centered).\n\n normalize : boolean, optional, default False\n If True, the regressors X will be normalized before regression.\n This parameter is ignored when `fit_intercept` is set to False.\n When the regressors are normalized, note that this makes the\n hyperparameters learnt more robust and almost independent of the number\n of samples. The same property is not valid for standardized data.\n However, if you wish to standardize, please use\n `preprocessing.StandardScaler` before calling `fit` on an estimator\n with `normalize=False`.\n\n scoring : string, callable or None, optional, default: None\n A string (see model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``.\n\n cv : int, cross-validation generator or an iterable, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the efficient Leave-One-Out cross-validation\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n For integer/None inputs, if ``y`` is binary or multiclass,\n :class:`sklearn.model_selection.StratifiedKFold` is used, else, \n :class:`sklearn.model_selection.KFold` is used.\n\n Refer :ref:`User Guide <cross_validation>` for the various\n cross-validation strategies that can be used here.\n\n gcv_mode : {None, 'auto', 'svd', eigen'}, optional\n Flag indicating which strategy to use when performing\n Generalized Cross-Validation. Options are::\n\n 'auto' : use svd if n_samples > n_features or when X is a sparse\n matrix, otherwise use eigen\n 'svd' : force computation via singular value decomposition of X\n (does not work for sparse matrices)\n 'eigen' : force computation via eigendecomposition of X^T X\n\n The 'auto' mode is the default and is intended to pick the cheaper\n option of the two depending upon the shape and format of the training\n data.\n\n store_cv_values : boolean, default=False\n Flag indicating if the cross-validation values corresponding to\n each alpha should be stored in the `cv_values_` attribute (see\n below). This flag is only compatible with `cv=None` (i.e. using\n Generalized Cross-Validation).\n\n Attributes\n ----------\n cv_values_ : array, shape = [n_samples, n_alphas] or \\\n shape = [n_samples, n_targets, n_alphas], optional\n Cross-validation values for each alpha (if `store_cv_values=True` and \\\n `cv=None`). After `fit()` has been called, this attribute will \\\n contain the mean squared errors (by default) or the values of the \\\n `{loss,score}_func` function (if provided in the constructor).\n\n coef_ : array, shape = [n_features] or [n_targets, n_features]\n Weight vector(s).\n\n intercept_ : float | array, shape = (n_targets,)\n Independent term in decision function. Set to 0.0 if\n ``fit_intercept = False``.\n\n alpha_ : float\n Estimated regularization parameter.\n\n See also\n --------\n Ridge: Ridge regression\n RidgeClassifier: Ridge classifier\n RidgeClassifierCV: Ridge classifier with built-in cross validation\n \"\"\"\n pass\n\n\nclass RidgeClassifierCV(LinearClassifierMixin, _BaseRidgeCV):\n \"\"\"Ridge classifier with built-in cross-validation.\n\n By default, it performs Generalized Cross-Validation, which is a form of\n efficient Leave-One-Out cross-validation. Currently, only the n_features >\n n_samples case is handled efficiently.\n\n Read more in the :ref:`User Guide <ridge_regression>`.\n\n Parameters\n ----------\n alphas : numpy array of shape [n_alphas]\n Array of alpha values to try.\n Regularization strength; must be a positive float. Regularization\n improves the conditioning of the problem and reduces the variance of\n the estimates. Larger values specify stronger regularization.\n Alpha corresponds to ``C^-1`` in other linear models such as \n LogisticRegression or LinearSVC. \n\n fit_intercept : boolean\n Whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (e.g. data is expected to be already centered).\n\n normalize : boolean, optional, default False\n If True, the regressors X will be normalized before regression.\n This parameter is ignored when `fit_intercept` is set to False.\n When the regressors are normalized, note that this makes the\n hyperparameters learnt more robust and almost independent of the number\n of samples. The same property is not valid for standardized data.\n However, if you wish to standardize, please use\n `preprocessing.StandardScaler` before calling `fit` on an estimator\n with `normalize=False`.\n\n scoring : string, callable or None, optional, default: None\n A string (see model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``.\n\n cv : int, cross-validation generator or an iterable, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the efficient Leave-One-Out cross-validation\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n Refer :ref:`User Guide <cross_validation>` for the various\n cross-validation strategies that can be used here.\n\n class_weight : dict or 'balanced', optional\n Weights associated with classes in the form ``{class_label: weight}``.\n If not given, all classes are supposed to have weight one.\n\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``\n\n Attributes\n ----------\n cv_values_ : array, shape = [n_samples, n_alphas] or \\\n shape = [n_samples, n_responses, n_alphas], optional\n Cross-validation values for each alpha (if `store_cv_values=True` and\n `cv=None`). After `fit()` has been called, this attribute will contain \\\n the mean squared errors (by default) or the values of the \\\n `{loss,score}_func` function (if provided in the constructor).\n\n coef_ : array, shape = [n_features] or [n_targets, n_features]\n Weight vector(s).\n\n intercept_ : float | array, shape = (n_targets,)\n Independent term in decision function. Set to 0.0 if\n ``fit_intercept = False``.\n\n alpha_ : float\n Estimated regularization parameter\n\n See also\n --------\n Ridge: Ridge regression\n RidgeClassifier: Ridge classifier\n RidgeCV: Ridge regression with built-in cross validation\n\n Notes\n -----\n For multi-class classification, n_class classifiers are trained in\n a one-versus-all approach. Concretely, this is implemented by taking\n advantage of the multi-variate response support in Ridge.\n \"\"\"\n def __init__(self, alphas=(0.1, 1.0, 10.0), fit_intercept=True,\n normalize=False, scoring=None, cv=None, class_weight=None):\n super(RidgeClassifierCV, self).__init__(\n alphas=alphas, fit_intercept=fit_intercept, normalize=normalize,\n scoring=scoring, cv=cv)\n self.class_weight = class_weight\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit the ridge classifier.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n Training vectors, where n_samples is the number of samples\n and n_features is the number of features.\n\n y : array-like, shape (n_samples,)\n Target values.\n\n sample_weight : float or numpy array of shape (n_samples,)\n Sample weight.\n\n Returns\n -------\n self : object\n Returns self.\n \"\"\"\n self._label_binarizer = LabelBinarizer(pos_label=1, neg_label=-1)\n Y = self._label_binarizer.fit_transform(y)\n if not self._label_binarizer.y_type_.startswith('multilabel'):\n y = column_or_1d(y, warn=True)\n\n if self.class_weight:\n if sample_weight is None:\n sample_weight = 1.\n # modify the sample weights with the corresponding class weight\n sample_weight = (sample_weight *\n compute_sample_weight(self.class_weight, y))\n\n _BaseRidgeCV.fit(self, X, Y, sample_weight=sample_weight)\n return self\n\n @property\n def classes_(self):\n return self._label_binarizer.classes_\n" ]
[ [ "numpy.dot", "numpy.sqrt", "numpy.iinfo", "numpy.exp", "scipy.sparse.dia_matrix", "scipy.sparse.issparse", "scipy.linalg.lstsq", "numpy.atleast_1d", "numpy.ravel", "numpy.reciprocal", "numpy.zeros", "scipy.sparse.csc_matrix", "scipy.sparse.csr_matrix", "numpy.find_common_type", "numpy.sum", "scipy.sparse.isspmatrix", "numpy.empty", "numpy.ones", "numpy.average", "numpy.vstack" ], [ "numpy.dot", "scipy.linalg.svd", "numpy.sqrt", "numpy.asarray", "scipy.sparse.linalg.lsqr", "scipy.sparse.issparse", "scipy.sparse.linalg.cg", "scipy.linalg.lstsq", "numpy.atleast_1d", "scipy.linalg.eigh", "scipy.sparse.linalg.aslinearoperator", "numpy.argmax", "numpy.outer", "numpy.repeat", "scipy.linalg.solve", "numpy.zeros", "scipy.sparse.linalg.LinearOperator", "numpy.shape", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] } ]
StephenLouis/ISIC_2019
[ "340ece42915c770e68bc13da64698a7a8987420e" ]
[ "Data_Loader.py" ]
[ "import os\nimport torch\nimport csv\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom PIL import Image\n\ndef split_csv(file):\n data = []\n a_train_file = r'/home/huangyinyue/ISIC_2019/train.csv'\n a_test_file = r'/home/huangyinyue/ISIC_2019/test.csv'\n\n seed = 3\n np.random.seed(seed)\n train_indices = np.random.choice(25331, 20265, replace=False) # 设置随机数生成从0-150中随机挑选120个随机数\n test_indices = np.array(list(set(range(25331)) - set(train_indices)))\n # test_indices = np.random.choice(len(residue), 30, replace=False) # 如果训练集和测试集综合的数据加起来就是一整个数据集则不需要这个操作\n\n with open(file)as afile:\n a_reader = csv.reader(afile) # 从原始数据集中将所有数据读取出来并保存到a_reader中\n labels = next(a_reader) # 提取第一行设置为labels\n for row in a_reader: # 将a_reader中每一行的数据提取出来并保存到data的列表中\n data.append(row)\n\n # 生成训练数据集\n if not os.path.exists(a_train_file):\n with open(a_train_file, \"w\", newline='') as a_trian:\n writer = csv.writer(a_trian)\n writer.writerows([labels]) # 第一行为标签行\n writer.writerows(np.array(data)[train_indices])\n a_trian.close()\n\n # 生成测试数据集\n if not os.path.exists(a_test_file):\n with open(a_test_file, \"w\", newline='')as a_test:\n writer = csv.writer(a_test)\n writer.writerows([labels]) # 第一行为标签行\n writer.writerows(np.array(data)[test_indices])\n a_test.close()\n\n\ndef read_labels_csv(file,header=True):\n images = []\n num_categories = 0\n with open(file, 'r') as f:\n reader = csv.reader(f)\n rownum = 0\n for row in reader:\n if header and rownum == 0:\n header = row\n else:\n if num_categories == 0:\n num_categories = len(row) - 1\n name = row[0]\n labels = (np.asarray(row[1:num_categories + 1])).astype(np.float32)\n labels = torch.from_numpy(labels)\n item = (name, labels)\n images.append(item)\n rownum += 1\n return images\n\nclass ISICDataset(Dataset):\n def __init__(self,csv_file,image_path,transform=None):\n self.images = read_labels_csv(csv_file)\n self.root_dir = image_path\n self.transform = transform\n\n def __len__(self):\n return len(self.images)\n\n def __getitem__(self, index):\n image_name,target = self.images[index]\n # print(os.path.join(self.root_dir,image_name+'.jpg'))\n image = Image.open(os.path.join(self.root_dir,image_name+'.jpg')).convert('RGB')\n if self.transform is not None:\n image = self.transform(image)\n\n return image,target\n\n\nif __name__ == '__main__':\n split_csv(file=r\"/home/huangyinyue/ISIC_2019/ISIC_2019_Training_GroundTruth.csv\")\n" ]
[ [ "numpy.random.seed", "numpy.random.choice", "numpy.asarray", "torch.from_numpy", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
daniyaljamal/Personality-prediction-based-on-video-using-CNN
[ "0f1052d09fe14c73e38ac529ad35e4e98a8d859e" ]
[ "data preprocessing/MTCNN2.py" ]
[ "# extract and plot each detected face in a photograph\nfrom facenet_pytorch import MTCNN\nfrom cv2 import cv2\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom tqdm.notebook import tqdm\nimport os\nimport tensorflow as tf\nfrom torchvision import models\nimport torch\nfrom torchvision import transforms\nfrom pathlib import Path\n\ndef getface_from_video(path):\n \n # Create face detector\n mtcnn = MTCNN(margin=20, post_process=False)\n\n # Load a video\n v_cap = cv2.VideoCapture(path)\n v_len = int(v_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n # Loop through video, taking a handful of frames to form a batch\n frames = []\n for i in tqdm(range(v_len)):\n \n # Load frame\n success = v_cap.grab()\n if i % 50 == 0:\n success, frame = v_cap.retrieve()\n else:\n continue\n if not success:\n continue\n \n # Add to batch\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frames.append(Image.fromarray(frame))\n\n # Detect faces in batch\n try:\n faces = mtcnn(frames)\n for i in range(len(faces)):\n plt.imshow(faces[i].permute(1, 2, 0).int().numpy())\n plt.axis('off')\n #plt.show()\n except:\n print(\"Error in detection\")\n return plt\n\ndir(models)\nos.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\"\n\nTRAIN_DIR = \"E:\\\\F Y P\\\\Personality prediction using image processing\\\\datasets\\\\First Impressions V2 (CVPR'17)\\\\train\\\\Extracted\\\\train videos\\\\\"\nTEST_DIR = \"E:\\\\F Y P\\\\Personality prediction using image processing\\\\datasets\\\\First Impressions V2 (CVPR'17)\\\\test\\\\Extracted\\\\test videos\\\\\"\nVAL_DIR = \"E:\\\\F Y P\\\\Personality prediction using image processing\\\\datasets\\\\First Impressions V2 (CVPR'17)\\\\validate\\\\Extracted\\\\validation videos\\\\\"\nPIC_TRAIN_DIR = \"E:\\\\F Y P\\\\Personality prediction using image processing\\\\datasets\\\\First Impressions V2 (CVPR'17)\\\\train\\\\Extracted\\\\face\\\\\"\nPIC_TEST_DIR = \"E:\\\\F Y P\\\\Personality prediction using image processing\\\\datasets\\\\First Impressions V2 (CVPR'17)\\\\test\\\\Extracted\\\\face\\\\\"\nPIC_VAL_DIR = \"E:\\\\F Y P\\\\Personality prediction using image processing\\\\datasets\\\\First Impressions V2 (CVPR'17)\\\\validate\\\\Extracted\\\\face\\\\\"\n\ntrain_videos = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)]\ntest_videos = [TEST_DIR+i for i in os.listdir(TEST_DIR)]\nval_videos = [VAL_DIR+i for i in os.listdir(VAL_DIR)]\n\ni=0\nwhile (i<len(val_videos)):\n #print(train_videos[i])\n fig = getface_from_video(val_videos[i])\n fig.savefig(os.path.splitext(PIC_VAL_DIR+Path(val_videos[i]).name)[0] +\".jpg\", bbox_inches='tight')\n i+=1\n" ]
[ [ "matplotlib.pyplot.axis" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Igor-ID/Image-Compression
[ "e54881b62f258260baa7036cdd3b264b0d8adf05" ]
[ "wavelet_compress.py" ]
[ "import pywt\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nimport numpy as np\n\n\"\"\"Image compression using discrete Wavelet transform.\"\"\"\n\nplt.rcParams['figure.figsize'] = [8, 8]\nplt.rcParams.update({'font.size': 18})\n\nim = imread('data/dog.jpg')\nim_gray = np.mean(im, -1) # convert RGB to gray scale\n\n# Wavelet Compression\nn = 4\n# Use Daubechies 1 wavelet family.\nw = 'db1'\ncoeffs = pywt.wavedec2(im_gray, wavelet=w, level=n)\ncoeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)\nCsort = np.sort(np.abs(coeff_arr.reshape(-1)))\n\nfor keep in (0.1, 0.05, 0.01, 0.005):\n thresh = Csort[int(np.floor((1 - keep) * len(Csort)))]\n ind = np.abs(coeff_arr) > thresh\n Cfilt = coeff_arr * ind # Threshold small indices\n\n coeffs_filt = pywt.array_to_coeffs(Cfilt, coeff_slices, output_format='wavedec2')\n\n # Plot reconstruction\n Arecon = pywt.waverec2(coeffs_filt, wavelet=w)\n plt.figure()\n plt.imshow(Arecon.astype('uint8'), cmap='gray')\n plt.axis('off')\n plt.title('keep = ' + str(keep))\n\nplt.show()\n# Conclusion. As we can see, image compression works batter when we using Wavelets in compare with FFT\n" ]
[ [ "numpy.abs", "matplotlib.image.imread", "numpy.mean", "matplotlib.pyplot.axis", "matplotlib.pyplot.rcParams.update", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
drigols/Studies
[ "9c293156935b491ded24be6b511daac67fd43538", "9c293156935b491ded24be6b511daac67fd43538", "9c293156935b491ded24be6b511daac67fd43538", "9c293156935b491ded24be6b511daac67fd43538", "9c293156935b491ded24be6b511daac67fd43538", "9c293156935b491ded24be6b511daac67fd43538" ]
[ "modules/ai-codes/modules/knn/src/iris-v1.py", "modules/math-codes/modules/linear-algebra/matrices/src/sparsity.py", "modules/math-codes/modules/linear-algebra/vectors/src/vector_addition.py", "modules/ai-codes/modules/logistic-regression/src/deodorant_instant_liking_gridSearchCV.py", "modules/ai-codes/modules/linear-regression/src/houses_predict.py", "modules/ai-codes/modules/regression/src/galtonDataset.py" ]
[ "########################################################\n# Rodrigo Leite - drigols #\n# Last update: 31/10/2021 #\n########################################################\n\nfrom sklearn.datasets import load_iris\nimport pandas as pd\n\niris = load_iris()\n\nx = pd.DataFrame(iris.data, columns=[iris.feature_names])\ny = pd.Series(iris.target)\n\nprint(\"Load Iris dataset dimensions: {0}\".format(x.shape))\nprint(\"Load Iris dataset features:\\n\", x.head(10))\n\n", "########################################################\n# Rodrigo Leite - drigols #\n# Last update: 02/03/2021 #\n########################################################\n\nfrom scipy.sparse import csr_matrix\nfrom numpy import count_nonzero\nfrom numpy import array\n\n# Create dense matrix\ndense_matrix = array(\n [\n [1, 0, 0, 1, 0, 0],\n [0, 0, 2, 0, 0, 1],\n [0, 0, 0, 2, 0, 0]\n ]\n)\n\n# Convert to sparse matrix (CSR method)\nsparse_matrix = csr_matrix(dense_matrix)\nprint(\"Sparse Matrix:\\n\", sparse_matrix)\nprint(\"Sparse Matrix shape:\", sparse_matrix.shape)\n\n# Reconstruct dense matrix\ndense_matrix_two = sparse_matrix.todense()\nprint(\"\\nDense Matrix:\\n\", dense_matrix_two)\nprint(\"Dense Matrix shape:\\n\", dense_matrix_two.shape)\n\n# Calculate sparsity\nsparsity = 1.0 - count_nonzero(dense_matrix) / dense_matrix.size\nprint(\"\\nMatrix Sparsity\", sparsity)\n", "import numpy as np\nimport matplotlib.pyplot as plt\n\nv = np.array([2, 1]) # Cria o Vetor \"v\" com array NumPy.\ns = np.array([-3, 2]) # Cria o Vetor \"s\" com array NumPy.\nz = v + s # soma os vetores \"v\" e \"s\".\nvectors = np.array([v, s, z]) # Adiciona os Vetores \"v\", \"s\" e \"z\" dentro de um terceiro Vetor.\n\nprint(\"v = {0}\\n s = {1}\\n v + s = {2}\\n v + s + z = {3}\".format(v, s, z, vectors))\n\n# Cria um plot com quiver() para exibir os 3 vetores.\nplt.quiver(0, 0, vectors[:,0], vectors[:,1], color=['r', 'b', 'g'], scale=10)\nplt.axis('equal') \nplt.xlabel('Coordenadas - X')\nplt.ylabel('Coordenadas - Y')\nplt.grid()\nplt.savefig('../images/plot-03.png', format='png')\nplt.show()\n", "########################################################\n# Rodrigo Leite - drigols #\n# Last update: 04/10/2021 #\n########################################################\n\nif __name__==\"__main__\":\n\n from sklearn.linear_model import LogisticRegression\n from sklearn.model_selection import GridSearchCV\n import pandas as pd\n import numpy as np\n\n pd.set_option('display.max_columns', 64)\n pd.set_option('display.max_rows', 64)\n df = pd.read_csv('../datasets/data_train_reduced.csv')\n\n # Drop Missing data > 20%\n df.drop(['q8.2','q8.8','q8.9','q8.10','q8.17','q8.18','q8.20'], axis=1, inplace=True)\n\n # Remove others unuseful columns (variables).\n df.drop(['Respondent.ID'], axis=1, inplace=True)\n df.drop('q1_1.personal.opinion.of.this.Deodorant', axis=1, inplace=True) # Remove 100% Accuracy (Personal Opinion).\n\n # Replace (fill) 20% missing data per median.\n df['q8.12'].fillna(df['q8.12'].median(), inplace=True)\n df['q8.7'].fillna(df['q8.7'].median(), inplace=True)\n\n df.drop(['Product'], axis=1, inplace=True) # Drop column \"product\": ERROR Deodorant J \n\n y = df['Instant.Liking']\n x = df.drop('Instant.Liking', axis=1)\n\n C_values = np.array([0.01, 0.1, 0.5, 1, 2, 3, 5, 10, 20, 50, 100])\n regularization = ['l1', 'l2']\n grid_values = {'C': C_values, 'penalty': regularization}\n\n model = LogisticRegression(max_iter=2000)\n\n logistic_regression_grid = GridSearchCV(estimator = model, param_grid = grid_values, cv = 5)\n logistic_regression_grid.fit(x, y)\n\n print(\"Best Accuracy:\", logistic_regression_grid.best_score_)\n print(\"Best C value:\", logistic_regression_grid.best_estimator_.C)\n print(\"Regularization:\", logistic_regression_grid.best_estimator_.penalty)\n", "from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom matplotlib import pyplot as plt\nimport pandas as pd\n\npd.set_option('display.max_columns', 21)\ndf = pd.read_csv('../datasets/kc_house_data.csv')\ndf = df.drop(['id', 'date', 'zipcode', 'lat', 'long'], axis=1)\n\ny = df['price']\nx = df.drop(['price'], axis=1)\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)\n\nmodel = LinearRegression()\nmodel.fit(x_train, y_train)\n\nr2 = model.score(x_test, y_test)\nprint('Coefficient of Determination: R^2: {0}'.format(r2))\n", "import pandas as pd\n\nwith open('../datasets/Galton_Dataset.txt', 'r') as f:\n data = pd.read_table(f, sep='\\s+')\n\nprint(data.head(10))\n" ]
[ [ "sklearn.datasets.load_iris", "pandas.Series", "pandas.DataFrame" ], [ "numpy.count_nonzero", "numpy.array", "scipy.sparse.csr_matrix" ], [ "matplotlib.pyplot.savefig", "matplotlib.pyplot.grid", "matplotlib.pyplot.axis", "matplotlib.pyplot.quiver", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "sklearn.model_selection.GridSearchCV", "pandas.read_csv", "sklearn.linear_model.LogisticRegression", "pandas.set_option", "numpy.array" ], [ "sklearn.linear_model.LinearRegression", "pandas.set_option", "pandas.read_csv", "sklearn.model_selection.train_test_split" ], [ "pandas.read_table" ] ]
[ { "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": [], "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": [] }, { "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": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
tableClothed/face-filters
[ "8b236643b4e22a925df6a1c299f3887fdedb3e8e" ]
[ "flask/camera.py" ]
[ "import cv2\nimport numpy as np\nimport dlib\nfrom imutils import face_utils, translate\n\nclass Camera(object):\n\tdef __init__(self):\n\t\tself.camera = cv2.VideoCapture(0)\n\n\t\tp = \"../data/shape_predictor_68_face_landmarks.dat\"\n\t\tself.detector = dlib.get_frontal_face_detector()\n\t\tself.predictor = dlib.shape_predictor(p)\n\t\tself.effect = \"contours\"\n\n\n\tdef __del__(self):\n\t\tself.camera.release()\n\n\n\tdef return_jpg(self, frame):\n\t\tret, jpeg = cv2.imencode('.jpeg', frame)\n\t\treturn jpeg.tobytes()\n\n\n\n\tdef return_effect(self):\n\t\tif self.effect == \"contours\":\n\t\t\tframe = self.effect_canny()\n\n\t\telif self.effect == \"baby\":\n\t\t\tframe = self.effect_baby_face()\n\n\t\telif self.effect == \"blurr\":\n\t\t\tframe = self.effect_bluring_face()\n\n\t\telif self.effect == \"cartoon\":\n\t\t\tframe = self.effect_cartoon()\n\n\t\telif self.effect == \"doggy\":\t\n\t\t\tframe = self.effect_dog_face()\n\n\t\telif self.effect == \"large\":\t\n\t\t\tframe = self.effect_enlarged()\n\n\t\telif self.effect == \"mirrors\":\t\n\t\t\tframe = self.effect_mirror()\n\n\t\telif self.effect == \"triangle\":\t\n\t\t\tframe = self.effect_delaunay_triangle()\n\n\t\telif self.effect == \"glasses\":\t\n\t\t\tframe = self.effect_glasses()\n\n\t\treturn frame\n\n\n\n\t# ---------------\n\t# BABY FACE\n\t# ---------------\n\tdef effect_baby_face(self):\n\t\tret, frame = self.camera.read()\n\t\tif not ret:\n\t\t\treturn False\n\t\toffset = 4\n\t\tscale = 1.3\n\n\t\tframe_2 = frame.copy()\n\t\tmask = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\tmask = np.zeros(frame.shape, frame.dtype)\n\n\t\teye_mask = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\teye_mask = np.zeros(frame.shape, frame.dtype)\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\trects = self.detector(gray, 0)\n\n\t\tfor rect in rects:\n\t\t\tshape = self.predictor(gray, rect)\n\t\t\tshape = face_utils.shape_to_np(shape)\n\n\t\t\tl_eye, r_eye = shape[36:42], shape[42:48]\n\n\t\t\t(lx, ly, lw, lh) = cv2.boundingRect(l_eye)\n\t\t\t(rx, ry, rw, rh) = cv2.boundingRect(r_eye)\n\n\t\t\tl_eye = frame[ly-offset:ly+lh+offset, lx-offset:lx+lw+offset]\n\t\t\tr_eye = frame[ry-offset:ry+rh+offset, rx-offset:rx+rw+offset]\n\n\t\t\tcenter_ly = lx + int(lw / 2)\n\t\t\tcenter_lx = ly + int(lh / 2) + 20\n\t\t\tcenter_ry = rx + int(rw / 2)\n\t\t\tcenter_rx = ry + int(rh / 2) + 20\n\n\t\t\tmouth = shape[48:69]\n\n\t\t\t(mx, my, mw, mh) = cv2.boundingRect(mouth)\n\t\t\tmouth = frame[my-offset:my+mh+offset, mx-offset:mx+mw+offset]\n\n\t\t\tcenter_my = mx + int(mw / 2)\n\t\t\tcenter_mx = my + int(mh / 2)\n\n\t\t\tly_scaled = int((l_eye.shape[1]*scale)/2)\n\t\t\tlx_scaled = int((l_eye.shape[0]*scale)/2)\n\t\t\try_scaled = int((r_eye.shape[1]*scale)/2)\n\t\t\trx_scaled = int((r_eye.shape[0]*scale)/2)\n\n\t\t\tl_eye = cv2.resize(l_eye, (ly_scaled*2, lx_scaled*2), interpolation = cv2.INTER_AREA)\n\t\t\tr_eye = cv2.resize(r_eye, (ry_scaled*2, rx_scaled*2), interpolation = cv2.INTER_AREA)\n\n\t\t\tframe[center_lx-lx_scaled:center_lx+lx_scaled, center_ly-ly_scaled:center_ly+ly_scaled] = l_eye\n\t\t\tmask[center_lx-lx_scaled:center_lx+lx_scaled, center_ly-ly_scaled:center_ly+ly_scaled] = 255\n\t\t\tframe[center_rx-rx_scaled:center_rx+rx_scaled, center_ry-ry_scaled:center_ry+ry_scaled] = r_eye\n\t\t\tmask[center_rx-rx_scaled:center_rx+rx_scaled, center_ry-ry_scaled:center_ry+ry_scaled] = 255\n\n\t\t\tfinal_center_x = int(np.mean([center_lx, center_rx]))\n\t\t\tfinal_center_y = int(np.mean([center_ly, center_ry]))\n\n\t\t\tframe = cv2.seamlessClone(frame, frame_2, mask, (final_center_y, final_center_x), cv2.NORMAL_CLONE)\n\n\t\treturn self.return_jpg(frame)\n\n\n\t# ------------------\n\t# ENLARGED EYES\n\t# ------------------\n\tdef effect_enlarged(self):\n\t\toffset = 4\n\t\tscale = 2\n\t\tret, frame = self.camera.read()\n\t\tif not ret:\n\t\t\treturn False\n\t\tframe_2 = frame.copy()\n\n\t\tmask = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\tmask = np.zeros(frame.shape, frame.dtype)\n\n\t\tl_eye, r_eye = 0, 0\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\trects = self.detector(gray, 0)\n\n\t\tfor rect in rects:\n\t\t\tshape = self.predictor(gray, rect)\n\t\t\tshape = face_utils.shape_to_np(shape)\n\n\t\t\tl_eye, r_eye = shape[36:42], shape[42:48]\n\n\t\t\t(lx, ly, lw, lh) = cv2.boundingRect(l_eye)\n\t\t\t(rx, ry, rw, rh) = cv2.boundingRect(r_eye)\n\n\t\t\tl_eye = frame[ly-offset:ly+lh+offset, lx-offset:lx+lw+offset]\n\t\t\tr_eye = frame[ry-offset:ry+rh+offset, rx-offset:rx+rw+offset]\n\n\t\t\tcenter_ly = lx + int(lw / 2)\n\t\t\tcenter_lx = ly + int(lh / 2) + 20\n\t\t\tcenter_ry = rx + int(rw / 2)\n\t\t\tcenter_rx = ry + int(rh / 2) + 20\n\n\t\t\tmouth = shape[48:69]\n\n\t\t\t(mx, my, mw, mh) = cv2.boundingRect(mouth)\n\t\t\tmouth = frame[my-offset:my+mh+offset, mx-offset:mx+mw+offset]\n\n\t\t\tcenter_my = mx + int(mw / 2)\n\t\t\tcenter_mx = my + int(mh / 2)\n\n\t\t\tly_scaled = int((l_eye.shape[1]*1.7)/2)\n\t\t\tlx_scaled = int((l_eye.shape[0]*1.7)/2)\n\t\t\try_scaled = int((r_eye.shape[1]*1.7)/2)\n\t\t\trx_scaled = int((r_eye.shape[0]*1.7)/2)\n\n\t\t\tl_eye = cv2.resize(l_eye, (ly_scaled*2, lx_scaled*2), interpolation = cv2.INTER_AREA)\n\t\t\tr_eye = cv2.resize(r_eye, (ry_scaled*2, rx_scaled*2), interpolation = cv2.INTER_AREA)\n\n\t\t\tmy_scaled = int((mouth.shape[1]*scale)/2)\n\t\t\tmx_scaled = int((mouth.shape[0]*scale)/2)\n\n\t\t\tmouth = cv2.resize(mouth, (my_scaled*2, mx_scaled*2), interpolation = cv2.INTER_AREA)\n\n\t\t\tframe[center_mx-mx_scaled:center_mx+mx_scaled, center_my-my_scaled:center_my+my_scaled] = mouth\n\t\t\tmask[center_mx-mx_scaled:center_mx+mx_scaled, center_my-my_scaled:center_my+my_scaled] = 255\n\n\t\t\tframe[center_lx-lx_scaled:center_lx+lx_scaled, center_ly-ly_scaled:center_ly+ly_scaled] = l_eye\n\t\t\tmask[center_lx-lx_scaled:center_lx+lx_scaled, center_ly-ly_scaled:center_ly+ly_scaled] = 255\n\t\t\tframe[center_rx-rx_scaled:center_rx+rx_scaled, center_ry-ry_scaled:center_ry+ry_scaled] = r_eye\n\t\t\tmask[center_rx-rx_scaled:center_rx+rx_scaled, center_ry-ry_scaled:center_ry+ry_scaled] = 255\n\n\t\t\tfinal_center_x = int(np.mean([center_lx, center_mx, center_rx]))\n\t\t\tfinal_center_y = int(np.mean([center_ly, center_my, center_ry]))\n\n\t\t\tframe = cv2.seamlessClone(frame, frame_2, mask, (final_center_y, final_center_x), cv2.NORMAL_CLONE)\n\n\t\treturn self.return_jpg(frame)\n\n\t\n\t# ------------------\n\t# BLURRING FACE\n\t# ------------------\n\tdef effect_bluring_face(self):\n\t\tret, frame = self.camera.read()\n\t\tif not ret:\n\t\t\treturn False\n\t\tface = 0\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\trects = self.detector(gray, 0)\n\n\t\tfor rect in rects:\n\t\t\tshape = self.predictor(gray, rect)\n\t\t\tshape = face_utils.shape_to_np(shape)\n\n\t\t\t(x, y, w, h) = face_utils.rect_to_bb(rect)\n\n\t\t\tface = frame[y:y+h, x:x+w]\n\t\t\tface = blurr_face(face)\n\t\t\tface = pixel_face(face)\n\n\t\t\tframe[y:y+h, x:x+w] = face\n\t\t\n\t\treturn self.return_jpg(frame)\n\n\n\t# ------------------------\n\t# DELAUNAY TRIANGLE\n\t# ------------------------\n\tdef effect_delaunay_triangle(self):\n\t\tret, frame = self.camera.read()\n\t\tif not ret:\n\t\t\treturn False\n\n\t\tjaw = [0, 17]\n\t\tr_eyebrow, l_eyebrow = [18, 22], [23, 27]\n\t\tnose = [28, 36]\n\t\tr_eye, l_eye = [37, 42], [43, 48]\n\t\tmouth = [49, 68]\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\tmask = np.zeros_like(gray)\n\n\t\tfaces = self.detector(gray, 0)\n\t\tfor face in faces:\n\t\t landmark = self.predictor(gray, face)\n\t\t landmark_points = []\n\t\t for n in range(68):\n\t\t x = landmark.part(n).x\n\t\t y = landmark.part(n).y\n\t\t landmark_points.append((x, y))\n\n\t\t points = np.array(landmark_points, np.int32)\n\t\t convexhull = cv2.convexHull(points)\n\n\t\t cv2.fillConvexPoly(mask, convexhull, 255)\n\n\t\t face = cv2.bitwise_and(frame, frame, mask=mask)\n\n\t\t gray = delaunay_traingle(convexhull, landmark_points, gray, landmark_points)\n\n\t\treturn self.return_jpg(gray)\n\n\n\t# --------------\n\t# DOG FACE\n\t# --------------\n\tdef effect_dog_face(self):\n\t\tret, frame = self.camera.read()\n\t\tif not ret:\n\t\t\treturn False\n\t\tdog_nose = cv2.imread(\"../images/nose.png\", -1)\n\t\tdog_ears = cv2.imread(\"../images/ears.png\", -1)\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\trects = self.detector(gray, 0)\n\n\t\tfor rect in rects:\n\t\t\tshape = self.predictor(gray, rect)\n\t\t\tshape = face_utils.shape_to_np(shape)\n\n\t\t\tears_width = int(abs(shape[0][0] - shape[16][0]) * 1.5)\n\t\t\tears_height = int(ears_width * 0.4)\n\n\t\t\tears_x = int((shape[22][0] + shape[23][0])/2)\n\t\t\tears_y = shape[20][1] - 50\n\n\t\t\thalf_width = int(ears_width/2.0)\n\t\t\thalf_height = int(ears_height/2.0)\n\n\t\t\ty1, y2 = ears_y - half_height, ears_y + half_height\n\t\t\tx1, x2 = ears_x - half_width, ears_x + half_width\n\n\t\t\tdog_ears = cv2.resize(dog_ears, (half_width*2, half_height*2), interpolation = cv2.INTER_AREA)\n\n\t\t\talpha_s = dog_ears[:, :, 3] / 255.0\n\t\t\talpha_l = 1.0 - alpha_s\n\n\t\t\tfor c in range(0, 3):\n\t\t\t frame[y1:y2, x1:x2, c] = (alpha_s * dog_ears[:, :, c] + \n\t\t\t alpha_l * frame[y1:y2, x1:x2, c])\n\n\t\t\tnose_width = int(abs(shape[36][0] - shape[32][0]) * 1.7)\n\t\t\tnose_height = int(nose_width * 0.7)\n\n\t\t\t(nose_x, nose_y) = shape[30]\n\n\t\t\thalf_width = int(nose_width/2.0)\n\t\t\thalf_height = int(nose_height/2.0)\n\n\t\t\ty1, y2 = nose_y - half_height, nose_y + half_height\n\t\t\tx1, x2 = nose_x - half_width, nose_x + half_width\n\n\t\t\tdog_nose = cv2.resize(dog_nose, (half_width*2, half_height*2), interpolation = cv2.INTER_AREA)\n\n\t\t\talpha_s = dog_nose[:, :, 3] / 255.0\n\t\t\talpha_l = 1.0 - alpha_s\n\n\t\t\tfor c in range(0, 3):\n\t\t\t\tframe[y1:y2, x1:x2, c] = (alpha_s * dog_nose[:, :, c] + \n\t\t\t alpha_l * frame[y1:y2, x1:x2, c])\n\n\t\treturn self.return_jpg(frame)\n\n\n\t# -----------------\n\t# FUNNY GLASSES\n\t# -----------------\n\tdef effect_glasses(self):\n\t\tret, frame = self.camera.read()\n\t\tif not ret:\n\t\t\treturn False\n\t\tglasses = cv2.imread(\"../images/glasses.png\", -1)\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\trects = self.detector(gray, 0)\n\n\t\tfor rect in rects:\n\t\t\tshape = self.predictor(gray, rect)\n\t\t\tshape = face_utils.shape_to_np(shape)\n\n\t\tglasses_width = int(abs(shape[36][0] - shape[32][0]) * 4)\n\t\tglasses_height = int(glasses_width * 0.7)\n\n\t\t(glasses_x, glasses_y) = shape[30]\n\t\tglasses_y -= 20\n\n\t\thalf_width = int(glasses_width/2.0)\n\t\thalf_height = int(glasses_height/2.0)\n\n\t\ty1, y2 = glasses_y - half_height, glasses_y + half_height\n\t\tx1, x2 = glasses_x - half_width, glasses_x + half_width\n\n\t\tglasses = cv2.resize(glasses, (half_width*2, half_height*2), interpolation = cv2.INTER_AREA)\n\n\t\talpha_s = glasses[:, :, 3] / 255.0\n\t\talpha_l = 1.0 - alpha_s\n\n\t\tfor c in range(0, 3):\n\t\t\tframe[y1:y2, x1:x2, c] = (alpha_s * glasses[:, :, c] + \n\t\t alpha_l * frame[y1:y2, x1:x2, c])\n\n\n\t\treturn self.return_jpg(frame)\n\n\n\t# ----------------------\n\t# CARTOON-ISH\n\t# ----------------------\n\tdef effect_cartoon(self):\n\t\tret, frame = self.camera.read()\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\tgray = cv2.medianBlur(gray, 5)\n\t\tedges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 6)\n\n\t\tcolor = cv2.bilateralFilter(frame, 9, 150, 0.25)\n\t\tcartoon = cv2.bitwise_and(color, color, mask=edges)\n\n\t\treturn self.return_jpg(cartoon)\n\n\n\t# ------------\n\t# CANNY\n\t# ------------\n\tdef effect_canny(self):\n\t\tret, frame = self.camera.read()\n\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\tblurred = cv2.GaussianBlur(gray, (3, 3), 0)\n\n\t\tmedian = np.median(blurred)\n\t\tl_edge = int(max(0, 0.77 * median))\n\t\tu_edge = int(max(0, 1.33 * median))\n\n\t\tcanny = cv2.Canny(blurred, l_edge, u_edge)\n\n\t\treturn self.return_jpg(canny)\n\n\n\t# ------------\n\t# MIRRORS\n\t# ------------\n\tdef effect_mirror(self):\n\t\tret, frame = self.camera.read()\n\n\t\tsplit = frame.shape[1] // 2\n\t\tone_half = frame[:, :split, :]\n\t\tsec_half = cv2.flip(one_half, 1)\n\n\t\tframe = np.hstack((one_half, sec_half))\n\n\t\treturn self.return_jpg(frame)\n\n\n\n# ---------------------\n# ADDITIONAL FUNCTIONS\n# ---------------------\n\ndef blurr_face(image):\n\t(h, w) = image.shape[:2]\n\n\tkernel_w = int(w/3.0)\n\tkernel_h = int(h/3.0)\n\n\tif kernel_w % 2 == 0:\n\t\tkernel_w -= 1\n\telse: kernel_w = 5\n\n\tif kernel_h % 2 == 0:\n\t\tkernel_h -= 1\n\telse: kernel_h = 5\n\n\timg = cv2.GaussianBlur(image, (kernel_w, kernel_h), 0)\n\treturn img\n\n\ndef pixel_face(image):\n\tblocks = 16\n\t(h, w) = image.shape[:2]\n\txSteps = np.linspace(0, w, blocks+1, dtype=\"int\")\n\tySteps = np.linspace(0, h, blocks+1, dtype=\"int\")\n\n\tfor i in range(1, len(ySteps)):\n\t\tfor j in range(1, len(xSteps)):\n\t\t\tstartX = xSteps[j - 1]\n\t\t\tstartY = ySteps[i - 1]\n\t\t\tendX = xSteps[j]\n\t\t\tendY = ySteps[i]\n\n\t\t\troi = image[startY:endY, startX:endX]\n\t\t\t(B, G, R) = [int(x) for x in cv2.mean(roi)[:3]]\n\t\t\tcv2.rectangle(image, (startX, startY), (endX, endY),\n\t\t\t\t(B, G, R), -1)\n\n\treturn image\n\n\n\ndef delaunay_traingle(convexHull, points, frame, landmark_points):\n rect = cv2.boundingRect(convexHull)\n\n subdiv = cv2.Subdiv2D(rect)\n subdiv.insert(landmark_points)\n\n triangles = subdiv.getTriangleList()\n triangles = np.array(triangles, dtype=np.int32)\n\n\n for t in triangles:\n A, B, C = (t[0], t[1]), (t[2], t[3]), (t[4], t[5])\n\n cv2.line(frame, A, B, (255, 255, 255), 1, cv2.LINE_AA, 0)\n cv2.line(frame, B, C, (255, 255, 255), 1, cv2.LINE_AA, 0)\n cv2.line(frame, A, C, (255, 255, 255), 1, cv2.LINE_AA, 0)\n\n return frame" ]
[ [ "numpy.hstack", "numpy.linspace", "numpy.median", "numpy.zeros_like", "numpy.mean", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RudyVenguswamy/DALI
[ "1456689cbb06a6d6f2c46c3fd231d1c296808e00" ]
[ "dali/test/python/test_operator_gaussian_blur.py" ]
[ "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.types as types\nimport nvidia.dali.fn as fn\n\nimport numpy as np\nimport cv2\nfrom scipy.ndimage import convolve1d\nimport os\nfrom nose.tools import raises\nfrom nose.plugins.attrib import attr\n\nfrom test_utils import get_dali_extra_path, check_batch, compare_pipelines, RandomlyShapedDataIterator, dali_type\n\ndata_root = get_dali_extra_path()\nimages_dir = os.path.join(data_root, 'db', 'single', 'jpeg')\n\ntest_iters = 4\n\nshape_layout_axes_cases = [((20, 20, 30, 3), \"DHWC\", 3), ((20, 20, 30), \"\", 3),\n ((20, 30, 3), \"HWC\", 2), ((20, 30), \"HW\", 2),\n ((3, 30, 20), \"CWH\", 2), ((5, 20, 30, 3), \"FHWC\", 2),\n ((5, 10, 10, 7, 3), \"FDHWC\", 3), ((5, 3, 20, 30), \"FCHW\", 2),\n ((3, 5, 10, 10, 7), \"CFDHW\", 3)]\n\ndef to_batch(tl, batch_size):\n return [np.array(tl[i]) for i in range(batch_size)]\n\n\ndef to_cv_sigma(sigma, axes=2):\n if sigma is None:\n return (0,) * axes\n elif isinstance(sigma, (int, float)):\n return (sigma,) * axes\n elif (isinstance(sigma, np.ndarray) and len(sigma.shape) == 0):\n return (float(sigma),) * axes\n elif len(sigma) == 1:\n return (sigma[0],) * axes\n return tuple(reversed(sigma))\n\n\ndef to_cv_win_size(window_size, axes=2, sigma=None):\n if window_size is None:\n # when using cv2.getGaussianKernel we need to always provide window size\n if sigma is not None:\n sigma = to_cv_sigma(sigma, axes)\n return tuple([int(3 * s + 0.5) * 2 + 1 for s in sigma])\n return (0,) * axes\n elif isinstance(window_size, int):\n return (int(window_size),) * axes\n elif (isinstance(window_size, np.ndarray) and len(window_size.shape) == 0):\n return (int(window_size),) * axes\n elif len(window_size) == 1:\n return (int(window_size[0]),) * axes\n # OpenCV shape is the other way round: (width, height)\n return tuple(int(x) for x in reversed(window_size))\n\n\ndef gaussian_cv(image, sigma, window_size):\n sigma_x, sigma_y = to_cv_sigma(sigma)\n window_size_cv = to_cv_win_size(window_size)\n # compute on floats and round like a sane person (in mathematically complicit way)\n blurred = cv2.GaussianBlur(np.float32(image), window_size_cv, sigmaX=sigma_x, sigmaY=sigma_y)\n return np.uint8(blurred + 0.5)\n\n\ndef gaussian_baseline(image, sigma, window_size, axes=2, skip_axes=0, dtype=np.uint8):\n sigma_xyz = to_cv_sigma(sigma, axes)\n win_xyz = to_cv_win_size(window_size, axes, sigma)\n filters = [cv2.getGaussianKernel(win_xyz[i], sigma_xyz[i]) for i in range(axes)]\n filters = [np.float32(f).squeeze() for f in filters]\n filters.reverse()\n for i in reversed(range(axes)):\n axis = i + skip_axes\n image = convolve1d(np.float32(image), filters[i], axis, mode=\"mirror\")\n if dtype == np.float32:\n return image\n else:\n return dtype(image + 0.5)\n\n\ndef get_gaussian_pipe(batch_size, sigma, window_size, op_type):\n pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=0)\n with pipe:\n input, _ = fn.file_reader(file_root=images_dir, shard_id=0, num_shards=1)\n decoded = fn.image_decoder(input, device=\"cpu\", output_type=types.RGB)\n if op_type == \"gpu\":\n decoded = decoded.gpu()\n blurred = fn.gaussian_blur(decoded, device=op_type, sigma=sigma, window_size=window_size)\n pipe.set_outputs(blurred, decoded)\n return pipe\n\n\ndef check_gaussian_blur(batch_size, sigma, window_size, op_type=\"cpu\"):\n pipe = get_gaussian_pipe(batch_size, sigma, window_size, op_type)\n pipe.build()\n for _ in range(test_iters):\n result, input = pipe.run()\n if op_type == \"gpu\":\n result = result.as_cpu()\n input = input.as_cpu()\n input = to_batch(input, batch_size)\n baseline_cv = [gaussian_cv(img, sigma, window_size) for img in input]\n check_batch(result, baseline_cv, batch_size, max_allowed_error=1, expected_layout=\"HWC\")\n\n\ndef test_image_gaussian_blur():\n for dev in [\"cpu\", \"gpu\"]:\n for sigma in [1.0]:\n for window_size in [3, 5, None]:\n if sigma is None and window_size is None:\n continue\n yield check_gaussian_blur, 10, sigma, window_size, dev\n # OpenCv uses fixed values for small windows that are different that Gaussian funcion\n yield check_gaussian_blur, 10, None, 11, dev\n\n\n@attr('slow')\ndef test_image_gaussian_blur_slow():\n for dev in [\"cpu\", \"gpu\"]:\n for sigma in [1.0, [1.0, 2.0]]:\n for window_size in [3, 5, [7, 5], [5, 9], None]:\n if sigma is None and window_size is None:\n continue\n yield check_gaussian_blur, 10, sigma, window_size, dev\n # OpenCv uses fixed values for small windows that are different that Gaussian funcion\n for window_size in [15, [17, 31]]:\n yield check_gaussian_blur, 10, None, window_size, dev\n\n\ndef check_gaussian_blur_cpu_gpu(batch_size, sigma, window_size):\n cpu_pipe = get_gaussian_pipe(batch_size, sigma, window_size, \"cpu\")\n gpu_pipe = get_gaussian_pipe(batch_size, sigma, window_size, \"gpu\")\n compare_pipelines(cpu_pipe, gpu_pipe, batch_size, 16, max_allowed_error=1)\n\n\ndef test_gaussian_blur_cpu_gpu():\n for window_size in [5, [7, 13]]:\n yield check_gaussian_blur_cpu_gpu, 10, None, window_size\n\n@attr('slow')\ndef test_gaussian_blur_cpu_gpu_slow():\n for sigma in [1.0, [1.0, 2.0], None]:\n for window_size in [3, 5, [7, 5], [5, 9], 11, 15, 31, None]:\n if sigma is None and window_size is None:\n continue\n yield check_gaussian_blur_cpu_gpu, 10, sigma, window_size\n\n\ndef count_skip_axes(layout):\n if layout.startswith(\"FC\") or layout.startswith(\"CF\"):\n return 2\n elif layout.startswith(\"F\") or layout.startswith(\"C\"):\n return 1\n else:\n return 0\n\n\ndef check_generic_gaussian_blur(\n batch_size, sigma, window_size, shape, layout, axes, op_type=\"cpu\", in_dtype=np.uint8,\n out_dtype=types.NO_TYPE):\n pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=0)\n data = RandomlyShapedDataIterator(batch_size, max_shape=shape, dtype=in_dtype)\n # Extract the numpy type from DALI, we can have float32 or the same as input\n if out_dtype == types.NO_TYPE:\n result_type = in_dtype\n elif dali_type(in_dtype) == out_dtype:\n result_type = in_dtype\n else:\n result_type = np.float32\n with pipe:\n input = fn.external_source(data, layout=layout)\n if op_type == \"gpu\":\n input = input.gpu()\n blurred = fn.gaussian_blur(input, device=op_type, sigma=sigma,\n window_size=window_size, dtype=out_dtype)\n pipe.set_outputs(blurred, input)\n pipe.build()\n\n for _ in range(test_iters):\n result, input = pipe.run()\n if op_type == \"gpu\":\n result = result.as_cpu()\n input = input.as_cpu()\n input = to_batch(input, batch_size)\n skip_axes = count_skip_axes(layout)\n baseline = [\n gaussian_baseline(img, sigma, window_size, axes, skip_axes, dtype=result_type)\n for img in input]\n max_error = 1 if result_type != np.float32 else 1e-04\n check_batch(result, baseline, batch_size, max_allowed_error=max_error, expected_layout=layout)\n\n\n# Generate tests for single or per-axis sigma and window_size arguments\ndef generate_generic_cases(dev, t_in, t_out):\n for shape, layout, axes in shape_layout_axes_cases:\n for sigma in [1.0, [1.0, 2.0, 3.0]]:\n for window_size in [3, 5, [7, 5, 9], [3, 5, 9], None]:\n if isinstance(sigma, list):\n sigma = sigma[0:axes]\n if isinstance(window_size, list):\n window_size = window_size[0:axes]\n yield check_generic_gaussian_blur, 10, sigma, window_size, shape, layout, axes, dev, t_in, t_out\n for window_size in [11, 15]:\n yield check_generic_gaussian_blur, 10, None, window_size, shape, layout, axes, dev, t_in, t_out\n\n\ndef test_generic_gaussian_blur():\n for dev in [\"cpu\", \"gpu\"]:\n for (t_in, t_out) in [(np.uint8, types.NO_TYPE), (np.float32, types.FLOAT), (np.uint8, types.FLOAT)]:\n yield from generate_generic_cases(dev, t_in, t_out)\n\n\n@attr('slow')\ndef test_generic_gaussian_blur_slow():\n for dev in [\"cpu\", \"gpu\"]:\n for t_in in [np.uint8, np.int32, np.float32]:\n for t_out in [types.NO_TYPE, types.FLOAT, dali_type(t_in)]:\n yield from generate_generic_cases(dev, t_in, t_out)\n\n\ndef check_per_sample_gaussian_blur(\n batch_size, sigma_dim, window_size_dim, shape, layout, axes, op_type=\"cpu\"):\n pipe = Pipeline(batch_size=batch_size, num_threads=4, device_id=0)\n data = RandomlyShapedDataIterator(batch_size, max_shape=shape)\n with pipe:\n if sigma_dim is not None:\n sigma = fn.random.uniform(range=[0.5, 3], shape=[sigma_dim])\n sigma_arg = sigma\n else:\n # placeholder, so we can return something\n sigma = fn.coin_flip(probability=0)\n sigma_arg = None\n\n if window_size_dim is not None:\n window_radius = fn.random.uniform(range=[5, 10], shape=[window_size_dim])\n window_size = fn.cast(window_radius, dtype=types.INT32) * 2 + 1\n window_arg = window_size\n else:\n window_size = fn.coin_flip(probability=0)\n window_arg = None\n\n input = fn.external_source(data, layout=layout)\n if op_type == \"gpu\":\n input = input.gpu()\n blurred = fn.gaussian_blur(input, device=op_type, sigma=sigma_arg, window_size=window_arg)\n pipe.set_outputs(blurred, input, sigma, window_size)\n pipe.build()\n\n for _ in range(test_iters):\n result, input, sigma, window_size = pipe.run()\n if op_type == \"gpu\":\n result = result.as_cpu()\n input = input.as_cpu()\n input = to_batch(input, batch_size)\n sigma = to_batch(sigma, batch_size)\n window_size = to_batch(window_size, batch_size)\n baseline = []\n for i in range(batch_size):\n sigma_arg = sigma[i] if sigma is not None else None\n window_arg = window_size[i] if window_size_dim is not None else None\n skip_axes = count_skip_axes(layout)\n baseline.append(gaussian_baseline(input[i], sigma_arg, window_arg, axes, skip_axes))\n check_batch(result, baseline, batch_size, max_allowed_error=1, expected_layout=layout)\n\n\n# TODO(klecki): consider checking mixed ArgumentInput/Scalar value cases\ndef test_per_sample_gaussian_blur():\n for dev in [\"cpu\", \"gpu\"]:\n for shape, layout, axes in shape_layout_axes_cases:\n for sigma_dim in [None, 1, axes]:\n for window_size_dim in [None, 1, axes]:\n if sigma_dim is None and window_size_dim is None:\n continue\n yield check_per_sample_gaussian_blur, 10, sigma_dim, window_size_dim, shape, layout, axes, dev\n\n\n@raises(RuntimeError)\ndef check_fail_gaussian_blur(batch_size, sigma, window_size, shape, layout, axes, op_type, in_dtype=np.uint8, out_dtype=types.NO_TYPE):\n check_generic_gaussian_blur(batch_size, sigma, window_size, shape, layout, axes, op_type, in_dtype, out_dtype)\n\n\ndef test_fail_gaussian_blur():\n for dev in [\"cpu\", \"gpu\"]:\n # Check layout and channel placement errors\n for shape, layout, axes in [((20, 20, 30, 3), \"DHCW\", 3), ((5, 20, 30, 3), \"HFWC\", 2),\n ((5, 10, 10, 10, 7, 3), \"FWXYZC\", 4),\n ((5, 3, 20, 3, 30), \"FCHCW\", 2),\n ((5, 3, 20, 3, 30), \"FCCHW\", 2)]:\n yield check_fail_gaussian_blur, 10, 1.0, 11, shape, layout, axes, dev\n # Negative, disallowed or both unspecified values of sigma and window size\n yield check_fail_gaussian_blur, 10, 0.0, 0, (100, 20, 3), \"HWC\", 3, dev\n yield check_fail_gaussian_blur, 10, -1.0, 0, (100, 20, 3), \"HWC\", 3, dev\n yield check_fail_gaussian_blur, 10, 0.0, -11, (100, 20, 3), \"HWC\", 3, dev\n yield check_fail_gaussian_blur, 10, 0.0, 2, (100, 20, 3), \"HWC\", 3, dev\n" ]
[ [ "numpy.uint8", "numpy.array", "numpy.float32" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
stephenpascoe/arrow
[ "3efd08f0cbaa40d0d3a329b8613fb80ac022b985" ]
[ "python/pyarrow/tests/test_convert_pandas.py" ]
[ "# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport decimal\nimport json\nfrom collections import OrderedDict\nfrom datetime import date, datetime, time, timedelta\n\nimport numpy as np\nimport numpy.testing as npt\nimport pandas as pd\nimport pandas.util.testing as tm\nimport pytest\n\nimport pyarrow as pa\nimport pyarrow.types as patypes\nfrom pyarrow.compat import PY2\n\nfrom .pandas_examples import dataframe_with_arrays, dataframe_with_lists\n\n\ndef _alltypes_example(size=100):\n return pd.DataFrame({\n 'uint8': np.arange(size, dtype=np.uint8),\n 'uint16': np.arange(size, dtype=np.uint16),\n 'uint32': np.arange(size, dtype=np.uint32),\n 'uint64': np.arange(size, dtype=np.uint64),\n 'int8': np.arange(size, dtype=np.int16),\n 'int16': np.arange(size, dtype=np.int16),\n 'int32': np.arange(size, dtype=np.int32),\n 'int64': np.arange(size, dtype=np.int64),\n 'float32': np.arange(size, dtype=np.float32),\n 'float64': np.arange(size, dtype=np.float64),\n 'bool': np.random.randn(size) > 0,\n # TODO(wesm): Pandas only support ns resolution, Arrow supports s, ms,\n # us, ns\n 'datetime': np.arange(\"2016-01-01T00:00:00.001\", size,\n dtype='datetime64[ms]'),\n 'str': [str(x) for x in range(size)],\n 'str_with_nulls': [None] + [str(x) for x in range(size - 2)] + [None],\n 'empty_str': [''] * size\n })\n\n\ndef _check_pandas_roundtrip(df, expected=None, use_threads=False,\n expected_schema=None,\n check_dtype=True, schema=None,\n preserve_index=False,\n as_batch=False):\n klass = pa.RecordBatch if as_batch else pa.Table\n table = klass.from_pandas(df, schema=schema,\n preserve_index=preserve_index,\n nthreads=2 if use_threads else 1)\n result = table.to_pandas(use_threads=use_threads)\n\n if expected_schema:\n # all occurences of _check_pandas_roundtrip passes expected_schema\n # without the pandas generated key-value metadata, so we need to\n # add it before checking schema equality\n expected_schema = expected_schema.add_metadata(table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n if expected is None:\n expected = df\n\n tm.assert_frame_equal(result, expected, check_dtype=check_dtype,\n check_index_type=('equiv' if preserve_index\n else False))\n\n\ndef _check_series_roundtrip(s, type_=None, expected_pa_type=None):\n arr = pa.array(s, from_pandas=True, type=type_)\n\n if type_ is not None and expected_pa_type is None:\n expected_pa_type = type_\n\n if expected_pa_type is not None:\n assert arr.type == expected_pa_type\n\n result = pd.Series(arr.to_pandas(), name=s.name)\n if patypes.is_timestamp(arr.type) and arr.type.tz is not None:\n result = (result.dt.tz_localize('utc')\n .dt.tz_convert(arr.type.tz))\n\n tm.assert_series_equal(s, result)\n\n\ndef _check_array_roundtrip(values, expected=None, mask=None,\n type=None):\n arr = pa.array(values, from_pandas=True, mask=mask, type=type)\n result = arr.to_pandas()\n\n values_nulls = pd.isnull(values)\n if mask is None:\n assert arr.null_count == values_nulls.sum()\n else:\n assert arr.null_count == (mask | values_nulls).sum()\n\n if mask is None:\n tm.assert_series_equal(pd.Series(result), pd.Series(values),\n check_names=False)\n else:\n expected = pd.Series(np.ma.masked_array(values, mask=mask))\n tm.assert_series_equal(pd.Series(result), expected,\n check_names=False)\n\n\ndef _check_array_from_pandas_roundtrip(np_array):\n arr = pa.array(np_array, from_pandas=True)\n result = arr.to_pandas()\n npt.assert_array_equal(result, np_array)\n\n\nclass TestConvertMetadata(object):\n \"\"\"\n Conversion tests for Pandas metadata & indices.\n \"\"\"\n\n def test_non_string_columns(self):\n df = pd.DataFrame({0: [1, 2, 3]})\n table = pa.Table.from_pandas(df)\n assert table.column(0).name == '0'\n\n def test_from_pandas_with_columns(self):\n df = pd.DataFrame({0: [1, 2, 3], 1: [1, 3, 3], 2: [2, 4, 5]})\n\n table = pa.Table.from_pandas(df, columns=[0, 1])\n expected = pa.Table.from_pandas(df[[0, 1]])\n assert expected.equals(table)\n\n record_batch_table = pa.RecordBatch.from_pandas(df, columns=[0, 1])\n record_batch_expected = pa.RecordBatch.from_pandas(df[[0, 1]])\n assert record_batch_expected.equals(record_batch_table)\n\n def test_column_index_names_are_preserved(self):\n df = pd.DataFrame({'data': [1, 2, 3]})\n df.columns.names = ['a']\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns(self):\n columns = pd.MultiIndex.from_arrays([\n ['one', 'two'], ['X', 'Y']\n ])\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns_with_dtypes(self):\n columns = pd.MultiIndex.from_arrays(\n [\n ['one', 'two'],\n pd.DatetimeIndex(['2017-08-01', '2017-08-02']),\n ],\n names=['level_1', 'level_2'],\n )\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns_unicode(self):\n columns = pd.MultiIndex.from_arrays([[u'あ', u'い'], ['X', 'Y']])\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_integer_index_column(self):\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')])\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_index_metadata_field_name(self):\n # test None case, and strangely named non-index columns\n df = pd.DataFrame(\n [(1, 'a', 3.1), (2, 'b', 2.2), (3, 'c', 1.3)],\n index=pd.MultiIndex.from_arrays(\n [['c', 'b', 'a'], [3, 2, 1]],\n names=[None, 'foo']\n ),\n columns=['a', None, '__index_level_0__'],\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n col1, col2, col3, idx0, foo = js['columns']\n\n assert col1['name'] == 'a'\n assert col1['name'] == col1['field_name']\n\n assert col2['name'] is None\n assert col2['field_name'] == 'None'\n\n assert col3['name'] == '__index_level_0__'\n assert col3['name'] == col3['field_name']\n\n idx0_name, foo_name = js['index_columns']\n assert idx0_name == '__index_level_0__'\n assert idx0['field_name'] == idx0_name\n assert idx0['name'] is None\n\n assert foo_name == 'foo'\n assert foo['field_name'] == foo_name\n assert foo['name'] == foo_name\n\n def test_categorical_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.Index(list('def'), dtype='category')\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] is None\n assert column_indexes['pandas_type'] == 'categorical'\n assert column_indexes['numpy_type'] == 'int8'\n\n md = column_indexes['metadata']\n assert md['num_categories'] == 3\n assert md['ordered'] is False\n\n def test_string_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.Index(list('def'), name='stringz')\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] == 'stringz'\n assert column_indexes['name'] == column_indexes['field_name']\n assert column_indexes['pandas_type'] == ('bytes' if PY2 else 'unicode')\n assert column_indexes['numpy_type'] == 'object'\n\n md = column_indexes['metadata']\n\n if not PY2:\n assert len(md) == 1\n assert md['encoding'] == 'UTF-8'\n else:\n assert md is None or 'encoding' not in md\n\n def test_datetimetz_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.date_range(\n start='2017-01-01', periods=3, tz='America/New_York'\n )\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] is None\n assert column_indexes['pandas_type'] == 'datetimetz'\n assert column_indexes['numpy_type'] == 'datetime64[ns]'\n\n md = column_indexes['metadata']\n assert md['timezone'] == 'America/New_York'\n\n def test_datetimetz_row_index(self):\n df = pd.DataFrame({\n 'a': pd.date_range(\n start='2017-01-01', periods=3, tz='America/New_York'\n )\n })\n df = df.set_index('a')\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_categorical_row_index(self):\n df = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3]})\n df['a'] = df.a.astype('category')\n df = df.set_index('a')\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_duplicate_column_names_does_not_crash(self):\n df = pd.DataFrame([(1, 'a'), (2, 'b')], columns=list('aa'))\n with pytest.raises(ValueError):\n pa.Table.from_pandas(df)\n\n def test_dictionary_indices_boundscheck(self):\n # ARROW-1658. No validation of indices leads to segfaults in pandas\n indices = [[0, 1], [0, -1]]\n\n for inds in indices:\n arr = pa.DictionaryArray.from_arrays(inds, ['a'], safe=False)\n batch = pa.RecordBatch.from_arrays([arr], ['foo'])\n table = pa.Table.from_batches([batch, batch, batch])\n\n with pytest.raises(pa.ArrowInvalid):\n arr.to_pandas()\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas()\n\n def test_unicode_with_unicode_column_and_index(self):\n df = pd.DataFrame({u'あ': [u'い']}, index=[u'う'])\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_mixed_unicode_column_names(self):\n df = pd.DataFrame({u'あ': [u'い'], b'a': 1}, index=[u'う'])\n\n # TODO(phillipc): Should this raise?\n with pytest.raises(AssertionError):\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_binary_column_name(self):\n column_data = [u'い']\n key = u'あ'.encode('utf8')\n data = {key: column_data}\n df = pd.DataFrame(data)\n\n # we can't use _check_pandas_roundtrip here because our metdata\n # is always decoded as utf8: even if binary goes in, utf8 comes out\n t = pa.Table.from_pandas(df, preserve_index=True)\n df2 = t.to_pandas()\n assert df.values[0] == df2.values[0]\n assert df.index.values[0] == df2.index.values[0]\n assert df.columns[0] == key\n\n def test_multiindex_duplicate_values(self):\n num_rows = 3\n numbers = list(range(num_rows))\n index = pd.MultiIndex.from_arrays(\n [['foo', 'foo', 'bar'], numbers],\n names=['foobar', 'some_numbers'],\n )\n\n df = pd.DataFrame({'numbers': numbers}, index=index)\n\n table = pa.Table.from_pandas(df)\n result_df = table.to_pandas()\n tm.assert_frame_equal(result_df, df)\n\n def test_metadata_with_mixed_types(self):\n df = pd.DataFrame({'data': [b'some_bytes', u'some_unicode']})\n table = pa.Table.from_pandas(df)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'bytes'\n assert data_column['numpy_type'] == 'object'\n\n def test_list_metadata(self):\n df = pd.DataFrame({'data': [[1], [2, 3, 4], [5] * 7]})\n schema = pa.schema([pa.field('data', type=pa.list_(pa.int64()))])\n table = pa.Table.from_pandas(df, schema=schema)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'list[int64]'\n assert data_column['numpy_type'] == 'object'\n\n def test_decimal_metadata(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('394092382910493.12341234678'),\n -decimal.Decimal('314292388910493.12343437128'),\n ]\n })\n table = pa.Table.from_pandas(expected)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'decimal'\n assert data_column['numpy_type'] == 'object'\n assert data_column['metadata'] == {'precision': 26, 'scale': 11}\n\n def test_table_column_subset_metadata(self):\n # ARROW-1883\n df = pd.DataFrame({\n 'a': [1, 2, 3],\n 'b': pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')})\n table = pa.Table.from_pandas(df)\n\n table_subset = table.remove_column(1)\n result = table_subset.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n table_subset2 = table_subset.remove_column(1)\n result = table_subset2.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n # non-default index\n for index in [\n pd.Index(['a', 'b', 'c'], name='index'),\n pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')]:\n df = pd.DataFrame({'a': [1, 2, 3],\n 'b': [.1, .2, .3]}, index=index)\n table = pa.Table.from_pandas(df)\n\n table_subset = table.remove_column(1)\n result = table_subset.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n table_subset2 = table_subset.remove_column(1)\n result = table_subset2.to_pandas()\n tm.assert_frame_equal(result, df[['a']].reset_index(drop=True))\n\n def test_empty_list_metadata(self):\n # Create table with array of empty lists, forced to have type\n # list(string) in pyarrow\n c1 = [[\"test\"], [\"a\", \"b\"], None]\n c2 = [[], [], []]\n arrays = OrderedDict([\n ('c1', pa.array(c1, type=pa.list_(pa.string()))),\n ('c2', pa.array(c2, type=pa.list_(pa.string()))),\n ])\n rb = pa.RecordBatch.from_arrays(\n list(arrays.values()),\n list(arrays.keys())\n )\n tbl = pa.Table.from_batches([rb])\n\n # First roundtrip changes schema, because pandas cannot preserve the\n # type of empty lists\n df = tbl.to_pandas()\n tbl2 = pa.Table.from_pandas(df, preserve_index=True)\n md2 = json.loads(tbl2.schema.metadata[b'pandas'].decode('utf8'))\n\n # Second roundtrip\n df2 = tbl2.to_pandas()\n expected = pd.DataFrame(OrderedDict([('c1', c1), ('c2', c2)]))\n\n tm.assert_frame_equal(df2, expected)\n\n assert md2['columns'] == [\n {\n 'name': 'c1',\n 'field_name': 'c1',\n 'metadata': None,\n 'numpy_type': 'object',\n 'pandas_type': 'list[unicode]',\n },\n {\n 'name': 'c2',\n 'field_name': 'c2',\n 'metadata': None,\n 'numpy_type': 'object',\n 'pandas_type': 'list[empty]',\n },\n {\n 'name': None,\n 'field_name': '__index_level_0__',\n 'metadata': None,\n 'numpy_type': 'int64',\n 'pandas_type': 'int64',\n }\n ]\n\n\nclass TestConvertPrimitiveTypes(object):\n \"\"\"\n Conversion tests for primitive (e.g. numeric) types.\n \"\"\"\n\n def test_float_no_nulls(self):\n data = {}\n fields = []\n dtypes = [('f2', pa.float16()),\n ('f4', pa.float32()),\n ('f8', pa.float64())]\n num_values = 100\n\n for numpy_dtype, arrow_dtype in dtypes:\n values = np.random.randn(num_values)\n data[numpy_dtype] = values.astype(numpy_dtype)\n fields.append(pa.field(numpy_dtype, arrow_dtype))\n\n df = pd.DataFrame(data)\n schema = pa.schema(fields)\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_float_nulls(self):\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n dtypes = [('f2', pa.float16()),\n ('f4', pa.float32()),\n ('f8', pa.float64())]\n names = ['f2', 'f4', 'f8']\n expected_cols = []\n\n arrays = []\n fields = []\n for name, arrow_dtype in dtypes:\n values = np.random.randn(num_values).astype(name)\n\n arr = pa.array(values, from_pandas=True, mask=null_mask)\n arrays.append(arr)\n fields.append(pa.field(name, arrow_dtype))\n values[null_mask] = np.nan\n\n expected_cols.append(values)\n\n ex_frame = pd.DataFrame(dict(zip(names, expected_cols)),\n columns=names)\n\n table = pa.Table.from_arrays(arrays, names)\n assert table.schema.equals(pa.schema(fields))\n result = table.to_pandas()\n tm.assert_frame_equal(result, ex_frame)\n\n def test_float_nulls_to_ints(self):\n # ARROW-2135\n df = pd.DataFrame({\"a\": [1.0, 2.0, pd.np.NaN]})\n schema = pa.schema([pa.field(\"a\", pa.int16(), nullable=True)])\n table = pa.Table.from_pandas(df, schema=schema)\n assert table[0].to_pylist() == [1, 2, None]\n tm.assert_frame_equal(df, table.to_pandas())\n\n def test_integer_no_nulls(self):\n data = OrderedDict()\n fields = []\n\n numpy_dtypes = [\n ('i1', pa.int8()), ('i2', pa.int16()),\n ('i4', pa.int32()), ('i8', pa.int64()),\n ('u1', pa.uint8()), ('u2', pa.uint16()),\n ('u4', pa.uint32()), ('u8', pa.uint64()),\n ('longlong', pa.int64()), ('ulonglong', pa.uint64())\n ]\n num_values = 100\n\n for dtype, arrow_dtype in numpy_dtypes:\n info = np.iinfo(dtype)\n values = np.random.randint(max(info.min, np.iinfo(np.int_).min),\n min(info.max, np.iinfo(np.int_).max),\n size=num_values)\n data[dtype] = values.astype(dtype)\n fields.append(pa.field(dtype, arrow_dtype))\n\n df = pd.DataFrame(data)\n schema = pa.schema(fields)\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_all_integer_types(self):\n # Test all Numpy integer aliases\n data = OrderedDict()\n numpy_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',\n 'byte', 'ubyte', 'short', 'ushort', 'intc', 'uintc',\n 'int_', 'uint', 'longlong', 'ulonglong']\n for dtype in numpy_dtypes:\n data[dtype] = np.arange(12, dtype=dtype)\n df = pd.DataFrame(data)\n _check_pandas_roundtrip(df)\n\n def test_integer_with_nulls(self):\n # pandas requires upcast to float dtype\n\n int_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8']\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n\n expected_cols = []\n arrays = []\n for name in int_dtypes:\n values = np.random.randint(0, 100, size=num_values)\n\n arr = pa.array(values, mask=null_mask)\n arrays.append(arr)\n\n expected = values.astype('f8')\n expected[null_mask] = np.nan\n\n expected_cols.append(expected)\n\n ex_frame = pd.DataFrame(dict(zip(int_dtypes, expected_cols)),\n columns=int_dtypes)\n\n table = pa.Table.from_arrays(arrays, int_dtypes)\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, ex_frame)\n\n def test_array_from_pandas_type_cast(self):\n arr = np.arange(10, dtype='int64')\n\n target_type = pa.int8()\n\n result = pa.array(arr, type=target_type)\n expected = pa.array(arr.astype('int8'))\n assert result.equals(expected)\n\n def test_boolean_no_nulls(self):\n num_values = 100\n\n np.random.seed(0)\n\n df = pd.DataFrame({'bools': np.random.randn(num_values) > 0})\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_boolean_nulls(self):\n # pandas requires upcast to object dtype\n num_values = 100\n np.random.seed(0)\n\n mask = np.random.randint(0, 10, size=num_values) < 3\n values = np.random.randint(0, 10, size=num_values) < 5\n\n arr = pa.array(values, mask=mask)\n\n expected = values.astype(object)\n expected[mask] = None\n\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n ex_frame = pd.DataFrame({'bools': expected})\n\n table = pa.Table.from_arrays([arr], ['bools'])\n assert table.schema.equals(schema)\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, ex_frame)\n\n def test_float_object_nulls(self):\n arr = np.array([None, 1.5, np.float64(3.5)] * 5, dtype=object)\n df = pd.DataFrame({'floats': arr})\n expected = pd.DataFrame({'floats': pd.to_numeric(arr)})\n field = pa.field('floats', pa.float64())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected=expected,\n expected_schema=schema)\n\n def test_int_object_nulls(self):\n arr = np.array([None, 1, np.int64(3)] * 5, dtype=object)\n df = pd.DataFrame({'ints': arr})\n expected = pd.DataFrame({'ints': pd.to_numeric(arr)})\n field = pa.field('ints', pa.int64())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected=expected,\n expected_schema=schema)\n\n def test_boolean_object_nulls(self):\n arr = np.array([False, None, True] * 100, dtype=object)\n df = pd.DataFrame({'bools': arr})\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_all_nulls_cast_numeric(self):\n arr = np.array([None], dtype=object)\n\n def _check_type(t):\n a2 = pa.array(arr, type=t)\n assert a2.type == t\n assert a2[0].as_py() is None\n\n _check_type(pa.int32())\n _check_type(pa.float64())\n\n def test_half_floats_from_numpy(self):\n arr = np.array([1.5, np.nan], dtype=np.float16)\n a = pa.array(arr, type=pa.float16())\n x, y = a.to_pylist()\n assert isinstance(x, np.float16)\n assert x == 1.5\n assert isinstance(y, np.float16)\n assert np.isnan(y)\n\n a = pa.array(arr, type=pa.float16(), from_pandas=True)\n x, y = a.to_pylist()\n assert isinstance(x, np.float16)\n assert x == 1.5\n assert y is None\n\n\[email protected]('dtype',\n ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])\ndef test_array_integer_object_nulls_option(dtype):\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n values = np.random.randint(0, 100, size=num_values, dtype=dtype)\n\n array = pa.array(values, mask=null_mask)\n\n if null_mask.any():\n expected = values.astype('O')\n expected[null_mask] = None\n else:\n expected = values\n\n result = array.to_pandas(integer_object_nulls=True)\n\n np.testing.assert_equal(result, expected)\n\n\[email protected]('dtype',\n ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])\ndef test_table_integer_object_nulls_option(dtype):\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n values = np.random.randint(0, 100, size=num_values, dtype=dtype)\n\n array = pa.array(values, mask=null_mask)\n\n if null_mask.any():\n expected = values.astype('O')\n expected[null_mask] = None\n else:\n expected = values\n\n expected = pd.DataFrame({dtype: expected})\n\n table = pa.Table.from_arrays([array], [dtype])\n result = table.to_pandas(integer_object_nulls=True)\n\n tm.assert_frame_equal(result, expected)\n\n\nclass TestConvertDateTimeLikeTypes(object):\n \"\"\"\n Conversion tests for datetime- and timestamp-like types (date64, etc.).\n \"\"\"\n\n def test_timestamps_notimezone_no_nulls(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n field = pa.field('datetime64', pa.timestamp('ns'))\n schema = pa.schema([field])\n _check_pandas_roundtrip(\n df,\n expected_schema=schema,\n )\n\n def test_timestamps_notimezone_nulls(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n field = pa.field('datetime64', pa.timestamp('ns'))\n schema = pa.schema([field])\n _check_pandas_roundtrip(\n df,\n expected_schema=schema,\n )\n\n def test_timestamps_with_timezone(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123',\n '2006-01-13T12:34:56.432',\n '2010-08-13T05:46:57.437'],\n dtype='datetime64[ms]')\n })\n df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern')\n .to_frame())\n _check_pandas_roundtrip(df)\n\n _check_series_roundtrip(df['datetime64'])\n\n # drop-in a null and ns instead of ms\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern')\n .to_frame())\n\n _check_pandas_roundtrip(df)\n\n def test_python_datetime(self):\n # ARROW-2106\n date_array = [datetime.today() + timedelta(days=x) for x in range(10)]\n df = pd.DataFrame({\n 'datetime': pd.Series(date_array, dtype=object)\n })\n\n table = pa.Table.from_pandas(df)\n assert isinstance(table[0].data.chunk(0), pa.TimestampArray)\n\n result = table.to_pandas()\n expected_df = pd.DataFrame({\n 'datetime': date_array\n })\n tm.assert_frame_equal(expected_df, result)\n\n def test_python_datetime_subclass(self):\n\n class MyDatetime(datetime):\n # see https://github.com/pandas-dev/pandas/issues/21142\n nanosecond = 0.0\n\n date_array = [MyDatetime(2000, 1, 1, 1, 1, 1)]\n df = pd.DataFrame({\"datetime\": pd.Series(date_array, dtype=object)})\n\n table = pa.Table.from_pandas(df)\n assert isinstance(table[0].data.chunk(0), pa.TimestampArray)\n\n result = table.to_pandas()\n expected_df = pd.DataFrame({\"datetime\": date_array})\n\n # https://github.com/pandas-dev/pandas/issues/21142\n expected_df[\"datetime\"] = pd.to_datetime(expected_df[\"datetime\"])\n\n tm.assert_frame_equal(expected_df, result)\n\n def test_python_date_subclass(self):\n\n class MyDate(date):\n pass\n\n date_array = [MyDate(2000, 1, 1)]\n df = pd.DataFrame({\"date\": pd.Series(date_array, dtype=object)})\n\n table = pa.Table.from_pandas(df)\n assert isinstance(table[0].data.chunk(0), pa.Date32Array)\n\n result = table.to_pandas()\n expected_df = pd.DataFrame(\n {\"date\": np.array([\"2000-01-01\"], dtype=\"datetime64[ns]\")}\n )\n tm.assert_frame_equal(expected_df, result)\n\n def test_datetime64_to_date32(self):\n # ARROW-1718\n arr = pa.array([date(2017, 10, 23), None])\n c = pa.Column.from_array(\"d\", arr)\n s = c.to_pandas()\n\n arr2 = pa.Array.from_pandas(s, type=pa.date32())\n\n assert arr2.equals(arr.cast('date32'))\n\n @pytest.mark.parametrize('mask', [\n None,\n np.ones(3),\n np.array([True, False, False]),\n ])\n def test_pandas_datetime_to_date64(self, mask):\n s = pd.to_datetime([\n '2018-05-10T00:00:00',\n '2018-05-11T00:00:00',\n '2018-05-12T00:00:00',\n ])\n arr = pa.Array.from_pandas(s, type=pa.date64(), mask=mask)\n\n data = np.array([\n date(2018, 5, 10),\n date(2018, 5, 11),\n date(2018, 5, 12)\n ])\n expected = pa.array(data, mask=mask, type=pa.date64())\n\n assert arr.equals(expected)\n\n @pytest.mark.parametrize('mask', [\n None,\n np.ones(3),\n np.array([True, False, False])\n ])\n def test_pandas_datetime_to_date64_failures(self, mask):\n s = pd.to_datetime([\n '2018-05-10T10:24:01',\n '2018-05-11T10:24:01',\n '2018-05-12T10:24:01',\n ])\n\n expected_msg = 'Timestamp value had non-zero intraday milliseconds'\n with pytest.raises(pa.ArrowInvalid, match=expected_msg):\n pa.Array.from_pandas(s, type=pa.date64(), mask=mask)\n\n def test_date_infer(self):\n df = pd.DataFrame({\n 'date': [date(2000, 1, 1),\n None,\n date(1970, 1, 1),\n date(2040, 2, 26)]})\n table = pa.Table.from_pandas(df, preserve_index=False)\n field = pa.field('date', pa.date32())\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = pa.schema([field], metadata=table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n result = table.to_pandas()\n expected = df.copy()\n expected['date'] = pd.to_datetime(df['date'])\n tm.assert_frame_equal(result, expected)\n\n def test_date_mask(self):\n arr = np.array([date(2017, 4, 3), date(2017, 4, 4)],\n dtype='datetime64[D]')\n mask = [True, False]\n result = pa.array(arr, mask=np.array(mask))\n expected = np.array([None, date(2017, 4, 4)], dtype='datetime64[D]')\n expected = pa.array(expected, from_pandas=True)\n assert expected.equals(result)\n\n def test_date_objects_typed(self):\n arr = np.array([\n date(2017, 4, 3),\n None,\n date(2017, 4, 4),\n date(2017, 4, 5)], dtype=object)\n\n arr_i4 = np.array([17259, -1, 17260, 17261], dtype='int32')\n arr_i8 = arr_i4.astype('int64') * 86400000\n mask = np.array([False, True, False, False])\n\n t32 = pa.date32()\n t64 = pa.date64()\n\n a32 = pa.array(arr, type=t32)\n a64 = pa.array(arr, type=t64)\n\n a32_expected = pa.array(arr_i4, mask=mask, type=t32)\n a64_expected = pa.array(arr_i8, mask=mask, type=t64)\n\n assert a32.equals(a32_expected)\n assert a64.equals(a64_expected)\n\n # Test converting back to pandas\n colnames = ['date32', 'date64']\n table = pa.Table.from_arrays([a32, a64], colnames)\n table_pandas = table.to_pandas()\n\n ex_values = (np.array(['2017-04-03', '2017-04-04', '2017-04-04',\n '2017-04-05'],\n dtype='datetime64[D]')\n .astype('datetime64[ns]'))\n ex_values[1] = pd.NaT.value\n expected_pandas = pd.DataFrame({'date32': ex_values,\n 'date64': ex_values},\n columns=colnames)\n tm.assert_frame_equal(table_pandas, expected_pandas)\n\n def test_dates_from_integers(self):\n t1 = pa.date32()\n t2 = pa.date64()\n\n arr = np.array([17259, 17260, 17261], dtype='int32')\n arr2 = arr.astype('int64') * 86400000\n\n a1 = pa.array(arr, type=t1)\n a2 = pa.array(arr2, type=t2)\n\n expected = date(2017, 4, 3)\n assert a1[0].as_py() == expected\n assert a2[0].as_py() == expected\n\n @pytest.mark.xfail(reason=\"not supported ATM\",\n raises=NotImplementedError)\n def test_timedelta(self):\n # TODO(jreback): Pandas only support ns resolution\n # Arrow supports ??? for resolution\n df = pd.DataFrame({\n 'timedelta': np.arange(start=0, stop=3 * 86400000,\n step=86400000,\n dtype='timedelta64[ms]')\n })\n pa.Table.from_pandas(df)\n\n def test_pytime_from_pandas(self):\n pytimes = [time(1, 2, 3, 1356),\n time(4, 5, 6, 1356)]\n\n # microseconds\n t1 = pa.time64('us')\n\n aobjs = np.array(pytimes + [None], dtype=object)\n parr = pa.array(aobjs)\n assert parr.type == t1\n assert parr[0].as_py() == pytimes[0]\n assert parr[1].as_py() == pytimes[1]\n assert parr[2] is pa.NA\n\n # DataFrame\n df = pd.DataFrame({'times': aobjs})\n batch = pa.RecordBatch.from_pandas(df)\n assert batch[0].equals(parr)\n\n # Test ndarray of int64 values\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n\n a1 = pa.array(arr, type=pa.time64('us'))\n assert a1[0].as_py() == pytimes[0]\n\n a2 = pa.array(arr * 1000, type=pa.time64('ns'))\n assert a2[0].as_py() == pytimes[0]\n\n a3 = pa.array((arr / 1000).astype('i4'),\n type=pa.time32('ms'))\n assert a3[0].as_py() == pytimes[0].replace(microsecond=1000)\n\n a4 = pa.array((arr / 1000000).astype('i4'),\n type=pa.time32('s'))\n assert a4[0].as_py() == pytimes[0].replace(microsecond=0)\n\n def test_arrow_time_to_pandas(self):\n pytimes = [time(1, 2, 3, 1356),\n time(4, 5, 6, 1356),\n time(0, 0, 0)]\n\n expected = np.array(pytimes[:2] + [None])\n expected_ms = np.array([x.replace(microsecond=1000)\n for x in pytimes[:2]] +\n [None])\n expected_s = np.array([x.replace(microsecond=0)\n for x in pytimes[:2]] +\n [None])\n\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n\n null_mask = np.array([False, False, True], dtype=bool)\n\n a1 = pa.array(arr, mask=null_mask, type=pa.time64('us'))\n a2 = pa.array(arr * 1000, mask=null_mask,\n type=pa.time64('ns'))\n\n a3 = pa.array((arr / 1000).astype('i4'), mask=null_mask,\n type=pa.time32('ms'))\n a4 = pa.array((arr / 1000000).astype('i4'), mask=null_mask,\n type=pa.time32('s'))\n\n names = ['time64[us]', 'time64[ns]', 'time32[ms]', 'time32[s]']\n batch = pa.RecordBatch.from_arrays([a1, a2, a3, a4], names)\n arr = a1.to_pandas()\n assert (arr == expected).all()\n\n arr = a2.to_pandas()\n assert (arr == expected).all()\n\n arr = a3.to_pandas()\n assert (arr == expected_ms).all()\n\n arr = a4.to_pandas()\n assert (arr == expected_s).all()\n\n df = batch.to_pandas()\n expected_df = pd.DataFrame({'time64[us]': expected,\n 'time64[ns]': expected,\n 'time32[ms]': expected_ms,\n 'time32[s]': expected_s},\n columns=names)\n\n tm.assert_frame_equal(df, expected_df)\n\n def test_numpy_datetime64_columns(self):\n datetime64_ns = np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n _check_array_from_pandas_roundtrip(datetime64_ns)\n\n datetime64_us = np.array([\n '2007-07-13T01:23:34.123456',\n None,\n '2006-01-13T12:34:56.432539',\n '2010-08-13T05:46:57.437699'],\n dtype='datetime64[us]')\n _check_array_from_pandas_roundtrip(datetime64_us)\n\n datetime64_ms = np.array([\n '2007-07-13T01:23:34.123',\n None,\n '2006-01-13T12:34:56.432',\n '2010-08-13T05:46:57.437'],\n dtype='datetime64[ms]')\n _check_array_from_pandas_roundtrip(datetime64_ms)\n\n datetime64_s = np.array([\n '2007-07-13T01:23:34',\n None,\n '2006-01-13T12:34:56',\n '2010-08-13T05:46:57'],\n dtype='datetime64[s]')\n _check_array_from_pandas_roundtrip(datetime64_s)\n\n def test_numpy_datetime64_day_unit(self):\n datetime64_d = np.array([\n '2007-07-13',\n None,\n '2006-01-15',\n '2010-08-19'],\n dtype='datetime64[D]')\n _check_array_from_pandas_roundtrip(datetime64_d)\n\n def test_array_from_pandas_date_with_mask(self):\n m = np.array([True, False, True])\n data = pd.Series([\n date(1990, 1, 1),\n date(1991, 1, 1),\n date(1992, 1, 1)\n ])\n\n result = pa.Array.from_pandas(data, mask=m)\n\n expected = pd.Series([None, date(1991, 1, 1), None])\n assert pa.Array.from_pandas(expected).equals(result)\n\n def test_fixed_offset_timezone(self):\n df = pd.DataFrame({\n 'a': [\n pd.Timestamp('2012-11-11 00:00:00+01:00'),\n pd.NaT\n ]\n })\n _check_pandas_roundtrip(df)\n _check_serialize_components_roundtrip(df)\n\n\nclass TestConvertStringLikeTypes(object):\n \"\"\"\n Conversion tests for string and binary types.\n \"\"\"\n\n def test_unicode(self):\n repeats = 1000\n values = [u'foo', None, u'bar', u'mañana', np.nan]\n df = pd.DataFrame({'strings': values * repeats})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_bytes_to_binary(self):\n values = [u'qux', b'foo', None, bytearray(b'barz'), 'qux', np.nan]\n df = pd.DataFrame({'strings': values})\n\n table = pa.Table.from_pandas(df)\n assert table[0].type == pa.binary()\n\n values2 = [b'qux', b'foo', None, b'barz', b'qux', np.nan]\n expected = pd.DataFrame({'strings': values2})\n _check_pandas_roundtrip(df, expected)\n\n @pytest.mark.large_memory\n def test_bytes_exceed_2gb(self):\n v1 = b'x' * 100000000\n v2 = b'x' * 147483646\n\n # ARROW-2227, hit exactly 2GB on the nose\n df = pd.DataFrame({\n 'strings': [v1] * 20 + [v2] + ['x'] * 20\n })\n arr = pa.array(df['strings'])\n assert isinstance(arr, pa.ChunkedArray)\n assert arr.num_chunks == 2\n arr = None\n\n table = pa.Table.from_pandas(df)\n assert table[0].data.num_chunks == 2\n\n def test_fixed_size_bytes(self):\n values = [b'foo', None, bytearray(b'bar'), None, None, b'hey']\n df = pd.DataFrame({'strings': values})\n schema = pa.schema([pa.field('strings', pa.binary(3))])\n table = pa.Table.from_pandas(df, schema=schema)\n assert table.schema[0].type == schema[0].type\n assert table.schema[0].name == schema[0].name\n result = table.to_pandas()\n tm.assert_frame_equal(result, df)\n\n def test_fixed_size_bytes_does_not_accept_varying_lengths(self):\n values = [b'foo', None, b'ba', None, None, b'hey']\n df = pd.DataFrame({'strings': values})\n schema = pa.schema([pa.field('strings', pa.binary(3))])\n with pytest.raises(pa.ArrowInvalid):\n pa.Table.from_pandas(df, schema=schema)\n\n def test_variable_size_bytes(self):\n s = pd.Series([b'123', b'', b'a', None])\n _check_series_roundtrip(s, type_=pa.binary())\n\n def test_binary_from_bytearray(self):\n s = pd.Series([bytearray(b'123'), bytearray(b''), bytearray(b'a'),\n None])\n # Explicitly set type\n _check_series_roundtrip(s, type_=pa.binary())\n # Infer type from bytearrays\n _check_series_roundtrip(s, expected_pa_type=pa.binary())\n\n def test_table_empty_str(self):\n values = ['', '', '', '', '']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result1 = table.to_pandas(strings_to_categorical=False)\n expected1 = pd.DataFrame({'strings': values})\n tm.assert_frame_equal(result1, expected1, check_dtype=True)\n\n result2 = table.to_pandas(strings_to_categorical=True)\n expected2 = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result2, expected2, check_dtype=True)\n\n def test_selective_categoricals(self):\n values = ['', '', '', '', '']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n expected_str = pd.DataFrame({'strings': values})\n expected_cat = pd.DataFrame({'strings': pd.Categorical(values)})\n\n result1 = table.to_pandas(categories=['strings'])\n tm.assert_frame_equal(result1, expected_cat, check_dtype=True)\n result2 = table.to_pandas(categories=[])\n tm.assert_frame_equal(result2, expected_str, check_dtype=True)\n result3 = table.to_pandas(categories=('strings',))\n tm.assert_frame_equal(result3, expected_cat, check_dtype=True)\n result4 = table.to_pandas(categories=tuple())\n tm.assert_frame_equal(result4, expected_str, check_dtype=True)\n\n def test_table_str_to_categorical_without_na(self):\n values = ['a', 'a', 'b', 'b', 'c']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result = table.to_pandas(strings_to_categorical=True)\n expected = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result, expected, check_dtype=True)\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas(strings_to_categorical=True,\n zero_copy_only=True)\n\n def test_table_str_to_categorical_with_na(self):\n values = [None, 'a', 'b', np.nan]\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result = table.to_pandas(strings_to_categorical=True)\n expected = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result, expected, check_dtype=True)\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas(strings_to_categorical=True,\n zero_copy_only=True)\n\n # Regression test for ARROW-2101\n def test_array_of_bytes_to_strings(self):\n converted = pa.array(np.array([b'x'], dtype=object), pa.string())\n assert converted.type == pa.string()\n\n # Make sure that if an ndarray of bytes is passed to the array\n # constructor and the type is string, it will fail if those bytes\n # cannot be converted to utf-8\n def test_array_of_bytes_to_strings_bad_data(self):\n with pytest.raises(\n pa.lib.ArrowInvalid,\n match=(\"'(utf8|utf-8)' codec can't decode byte 0x80 \"\n \"in position 0: invalid start byte\")):\n pa.array(np.array([b'\\x80\\x81'], dtype=object), pa.string())\n\n def test_numpy_string_array_to_fixed_size_binary(self):\n arr = np.array([b'foo', b'bar', b'baz'], dtype='|S3')\n\n converted = pa.array(arr, type=pa.binary(3))\n expected = pa.array(list(arr), type=pa.binary(3))\n assert converted.equals(expected)\n\n mask = np.array([True, False, True])\n converted = pa.array(arr, type=pa.binary(3), mask=mask)\n expected = pa.array([b'foo', None, b'baz'], type=pa.binary(3))\n assert converted.equals(expected)\n\n with pytest.raises(pa.lib.ArrowInvalid,\n match='Got bytestring of length 3 \\(expected 4\\)'):\n arr = np.array([b'foo', b'bar', b'baz'], dtype='|S3')\n pa.array(arr, type=pa.binary(4))\n\n with pytest.raises(pa.lib.ArrowInvalid,\n match='Got bytestring of length 12 \\(expected 3\\)'):\n arr = np.array([b'foo', b'bar', b'baz'], dtype='|U3')\n pa.array(arr, type=pa.binary(3))\n\n\nclass TestConvertDecimalTypes(object):\n \"\"\"\n Conversion test for decimal types.\n \"\"\"\n decimal32 = [\n decimal.Decimal('-1234.123'),\n decimal.Decimal('1234.439')\n ]\n decimal64 = [\n decimal.Decimal('-129934.123331'),\n decimal.Decimal('129534.123731')\n ]\n decimal128 = [\n decimal.Decimal('394092382910493.12341234678'),\n decimal.Decimal('-314292388910493.12343437128')\n ]\n\n @pytest.mark.parametrize(('values', 'expected_type'), [\n pytest.param(decimal32, pa.decimal128(7, 3), id='decimal32'),\n pytest.param(decimal64, pa.decimal128(12, 6), id='decimal64'),\n pytest.param(decimal128, pa.decimal128(26, 11), id='decimal128')\n ])\n def test_decimal_from_pandas(self, values, expected_type):\n expected = pd.DataFrame({'decimals': values})\n table = pa.Table.from_pandas(expected, preserve_index=False)\n field = pa.field('decimals', expected_type)\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = pa.schema([field], metadata=table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n @pytest.mark.parametrize('values', [\n pytest.param(decimal32, id='decimal32'),\n pytest.param(decimal64, id='decimal64'),\n pytest.param(decimal128, id='decimal128')\n ])\n def test_decimal_to_pandas(self, values):\n expected = pd.DataFrame({'decimals': values})\n converted = pa.Table.from_pandas(expected)\n df = converted.to_pandas()\n tm.assert_frame_equal(df, expected)\n\n def test_decimal_fails_with_truncation(self):\n data1 = [decimal.Decimal('1.234')]\n type1 = pa.decimal128(10, 2)\n with pytest.raises(pa.ArrowInvalid):\n pa.array(data1, type=type1)\n\n data2 = [decimal.Decimal('1.2345')]\n type2 = pa.decimal128(10, 3)\n with pytest.raises(pa.ArrowInvalid):\n pa.array(data2, type=type2)\n\n def test_decimal_with_different_precisions(self):\n data = [\n decimal.Decimal('0.01'),\n decimal.Decimal('0.001'),\n ]\n series = pd.Series(data)\n array = pa.array(series)\n assert array.to_pylist() == data\n assert array.type == pa.decimal128(3, 3)\n\n array = pa.array(data, type=pa.decimal128(12, 5))\n expected = [decimal.Decimal('0.01000'), decimal.Decimal('0.00100')]\n assert array.to_pylist() == expected\n\n def test_decimal_with_None_explicit_type(self):\n series = pd.Series([decimal.Decimal('3.14'), None])\n _check_series_roundtrip(series, type_=pa.decimal128(12, 5))\n\n # Test that having all None values still produces decimal array\n series = pd.Series([None] * 2)\n _check_series_roundtrip(series, type_=pa.decimal128(12, 5))\n\n def test_decimal_with_None_infer_type(self):\n series = pd.Series([decimal.Decimal('3.14'), None])\n _check_series_roundtrip(series, expected_pa_type=pa.decimal128(3, 2))\n\n\nclass TestListTypes(object):\n \"\"\"\n Conversion tests for list<> types.\n \"\"\"\n\n def test_column_of_arrays(self):\n df, schema = dataframe_with_arrays()\n _check_pandas_roundtrip(df, schema=schema, expected_schema=schema)\n table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = schema.add_metadata(table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n for column in df.columns:\n field = schema.field_by_name(column)\n _check_array_roundtrip(df[column], type=field.type)\n\n def test_column_of_arrays_to_py(self):\n # Test regression in ARROW-1199 not caught in above test\n dtype = 'i1'\n arr = np.array([\n np.arange(10, dtype=dtype),\n np.arange(5, dtype=dtype),\n None,\n np.arange(1, dtype=dtype)\n ])\n type_ = pa.list_(pa.int8())\n parr = pa.array(arr, type=type_)\n\n assert parr[0].as_py() == list(range(10))\n assert parr[1].as_py() == list(range(5))\n assert parr[2].as_py() is None\n assert parr[3].as_py() == [0]\n\n def test_column_of_lists(self):\n df, schema = dataframe_with_lists()\n _check_pandas_roundtrip(df, schema=schema, expected_schema=schema)\n table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)\n\n # schema's metadata is generated by from_pandas conversion\n expected_schema = schema.add_metadata(table.schema.metadata)\n assert table.schema.equals(expected_schema)\n\n for column in df.columns:\n field = schema.field_by_name(column)\n _check_array_roundtrip(df[column], type=field.type)\n\n def test_column_of_lists_first_empty(self):\n # ARROW-2124\n num_lists = [[], [2, 3, 4], [3, 6, 7, 8], [], [2]]\n series = pd.Series([np.array(s, dtype=float) for s in num_lists])\n arr = pa.array(series)\n result = pd.Series(arr.to_pandas())\n tm.assert_series_equal(result, series)\n\n def test_column_of_lists_chunked(self):\n # ARROW-1357\n df = pd.DataFrame({\n 'lists': np.array([\n [1, 2],\n None,\n [2, 3],\n [4, 5],\n [6, 7],\n [8, 9]\n ], dtype=object)\n })\n\n schema = pa.schema([\n pa.field('lists', pa.list_(pa.int64()))\n ])\n\n t1 = pa.Table.from_pandas(df[:2], schema=schema)\n t2 = pa.Table.from_pandas(df[2:], schema=schema)\n\n table = pa.concat_tables([t1, t2])\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, df)\n\n def test_column_of_lists_chunked2(self):\n data1 = [[0, 1], [2, 3], [4, 5], [6, 7], [10, 11],\n [12, 13], [14, 15], [16, 17]]\n data2 = [[8, 9], [18, 19]]\n\n a1 = pa.array(data1)\n a2 = pa.array(data2)\n\n t1 = pa.Table.from_arrays([a1], names=['a'])\n t2 = pa.Table.from_arrays([a2], names=['a'])\n\n concatenated = pa.concat_tables([t1, t2])\n\n result = concatenated.to_pandas()\n expected = pd.DataFrame({'a': data1 + data2})\n\n tm.assert_frame_equal(result, expected)\n\n def test_column_of_lists_strided(self):\n df, schema = dataframe_with_lists()\n df = pd.concat([df] * 6, ignore_index=True)\n\n arr = df['int64'].values[::3]\n assert arr.strides[0] != 8\n\n _check_array_roundtrip(arr)\n\n def test_nested_lists_all_none(self):\n data = np.array([[None, None], None], dtype=object)\n\n arr = pa.array(data)\n expected = pa.array(list(data))\n assert arr.equals(expected)\n assert arr.type == pa.list_(pa.null())\n\n data2 = np.array([None, None, [None, None],\n np.array([None, None], dtype=object)],\n dtype=object)\n arr = pa.array(data2)\n expected = pa.array([None, None, [None, None], [None, None]])\n assert arr.equals(expected)\n\n def test_nested_lists_all_empty(self):\n # ARROW-2128\n data = pd.Series([[], [], []])\n arr = pa.array(data)\n expected = pa.array(list(data))\n assert arr.equals(expected)\n assert arr.type == pa.list_(pa.null())\n\n def test_nested_smaller_ints(self):\n # ARROW-1345, ARROW-2008, there were some type inference bugs happening\n # before\n data = pd.Series([np.array([1, 2, 3], dtype='i1'), None])\n result = pa.array(data)\n result2 = pa.array(data.values)\n expected = pa.array([[1, 2, 3], None], type=pa.list_(pa.int8()))\n assert result.equals(expected)\n assert result2.equals(expected)\n\n data3 = pd.Series([np.array([1, 2, 3], dtype='f4'), None])\n result3 = pa.array(data3)\n expected3 = pa.array([[1, 2, 3], None], type=pa.list_(pa.float32()))\n assert result3.equals(expected3)\n\n def test_infer_lists(self):\n data = OrderedDict([\n ('nan_ints', [[None, 1], [2, 3]]),\n ('ints', [[0, 1], [2, 3]]),\n ('strs', [[None, u'b'], [u'c', u'd']]),\n ('nested_strs', [[[None, u'b'], [u'c', u'd']], None])\n ])\n df = pd.DataFrame(data)\n\n expected_schema = pa.schema([\n pa.field('nan_ints', pa.list_(pa.int64())),\n pa.field('ints', pa.list_(pa.int64())),\n pa.field('strs', pa.list_(pa.string())),\n pa.field('nested_strs', pa.list_(pa.list_(pa.string())))\n ])\n\n _check_pandas_roundtrip(df, expected_schema=expected_schema)\n\n def test_infer_numpy_array(self):\n data = OrderedDict([\n ('ints', [\n np.array([0, 1], dtype=np.int64),\n np.array([2, 3], dtype=np.int64)\n ])\n ])\n df = pd.DataFrame(data)\n expected_schema = pa.schema([\n pa.field('ints', pa.list_(pa.int64()))\n ])\n\n _check_pandas_roundtrip(df, expected_schema=expected_schema)\n\n @pytest.mark.parametrize('t,data,expected', [\n (\n pa.int64,\n [[1, 2], [3], None],\n [None, [3], None]\n ),\n (\n pa.string,\n [[u'aaa', u'bb'], [u'c'], None],\n [None, [u'c'], None]\n ),\n (\n pa.null,\n [[None, None], [None], None],\n [None, [None], None]\n )\n ])\n def test_array_from_pandas_typed_array_with_mask(self, t, data, expected):\n m = np.array([True, False, True])\n\n s = pd.Series(data)\n result = pa.Array.from_pandas(s, mask=m, type=pa.list_(t()))\n\n assert pa.Array.from_pandas(expected,\n type=pa.list_(t())).equals(result)\n\n def test_empty_list_roundtrip(self):\n empty_list_array = np.empty((3,), dtype=object)\n empty_list_array.fill([])\n\n df = pd.DataFrame({'a': np.array(['1', '2', '3']),\n 'b': empty_list_array})\n tbl = pa.Table.from_pandas(df)\n\n result = tbl.to_pandas()\n\n tm.assert_frame_equal(result, df)\n\n def test_array_from_nested_arrays(self):\n df, schema = dataframe_with_arrays()\n for field in schema:\n arr = df[field.name].values\n expected = pa.array(list(arr), type=field.type)\n result = pa.array(arr)\n assert result.type == field.type # == list<scalar>\n assert result.equals(expected)\n\n\nclass TestConvertStructTypes(object):\n \"\"\"\n Conversion tests for struct types.\n \"\"\"\n\n def test_to_pandas(self):\n ints = pa.array([None, 2, 3], type=pa.int64())\n strs = pa.array([u'a', None, u'c'], type=pa.string())\n bools = pa.array([True, False, None], type=pa.bool_())\n arr = pa.StructArray.from_arrays(\n [ints, strs, bools],\n ['ints', 'strs', 'bools'])\n\n expected = pd.Series([\n {'ints': None, 'strs': u'a', 'bools': True},\n {'ints': 2, 'strs': None, 'bools': False},\n {'ints': 3, 'strs': u'c', 'bools': None},\n ])\n\n series = pd.Series(arr.to_pandas())\n tm.assert_series_equal(series, expected)\n\n def test_from_numpy(self):\n dt = np.dtype([('x', np.int32),\n (('y_title', 'y'), np.bool_)])\n ty = pa.struct([pa.field('x', pa.int32()),\n pa.field('y', pa.bool_())])\n\n data = np.array([], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == []\n\n data = np.array([(42, True), (43, False)], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == [{'x': 42, 'y': True},\n {'x': 43, 'y': False}]\n\n # With mask\n arr = pa.array(data, mask=np.bool_([False, True]), type=ty)\n assert arr.to_pylist() == [{'x': 42, 'y': True}, None]\n\n # Trivial struct type\n dt = np.dtype([])\n ty = pa.struct([])\n\n data = np.array([], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == []\n\n data = np.array([(), ()], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == [{}, {}]\n\n def test_from_numpy_nested(self):\n dt = np.dtype([('x', np.dtype([('xx', np.int8),\n ('yy', np.bool_)])),\n ('y', np.int16)])\n ty = pa.struct([pa.field('x', pa.struct([pa.field('xx', pa.int8()),\n pa.field('yy', pa.bool_())])),\n pa.field('y', pa.int16())])\n\n data = np.array([], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == []\n\n data = np.array([((1, True), 2), ((3, False), 4)], dtype=dt)\n arr = pa.array(data, type=ty)\n assert arr.to_pylist() == [{'x': {'xx': 1, 'yy': True}, 'y': 2},\n {'x': {'xx': 3, 'yy': False}, 'y': 4}]\n\n @pytest.mark.large_memory\n def test_from_numpy_large(self):\n # Exercise rechunking + nulls\n target_size = 3 * 1024**3 # 4GB\n dt = np.dtype([('x', np.float64), ('y', 'object')])\n bs = 65536 - dt.itemsize\n block = b'.' * bs\n n = target_size // (bs + dt.itemsize)\n data = np.zeros(n, dtype=dt)\n data['x'] = np.random.random_sample(n)\n data['y'] = block\n # Add implicit nulls\n data['x'][data['x'] < 0.2] = np.nan\n\n ty = pa.struct([pa.field('x', pa.float64()),\n pa.field('y', pa.binary(bs))])\n arr = pa.array(data, type=ty, from_pandas=True)\n assert arr.num_chunks == 2\n\n def iter_chunked_array(arr):\n for chunk in arr.iterchunks():\n for item in chunk:\n yield item\n\n def check(arr, data, mask=None):\n assert len(arr) == len(data)\n xs = data['x']\n ys = data['y']\n for i, obj in enumerate(iter_chunked_array(arr)):\n try:\n d = obj.as_py()\n if mask is not None and mask[i]:\n assert d is None\n else:\n x = xs[i]\n if np.isnan(x):\n assert d['x'] is None\n else:\n assert d['x'] == x\n assert d['y'] == ys[i]\n except Exception:\n print(\"Failed at index\", i)\n raise\n\n check(arr, data)\n del arr\n\n # Now with explicit mask\n mask = np.random.random_sample(n) < 0.2\n arr = pa.array(data, type=ty, mask=mask, from_pandas=True)\n assert arr.num_chunks == 2\n\n check(arr, data, mask)\n del arr\n\n def test_from_numpy_bad_input(self):\n ty = pa.struct([pa.field('x', pa.int32()),\n pa.field('y', pa.bool_())])\n dt = np.dtype([('x', np.int32),\n ('z', np.bool_)])\n\n data = np.array([], dtype=dt)\n with pytest.raises(TypeError,\n match=\"Missing field 'y'\"):\n pa.array(data, type=ty)\n data = np.int32([])\n with pytest.raises(TypeError,\n match=\"Expected struct array\"):\n pa.array(data, type=ty)\n\n\nclass TestZeroCopyConversion(object):\n \"\"\"\n Tests that zero-copy conversion works with some types.\n \"\"\"\n\n def test_zero_copy_success(self):\n result = pa.array([0, 1, 2]).to_pandas(zero_copy_only=True)\n npt.assert_array_equal(result, [0, 1, 2])\n\n def test_zero_copy_dictionaries(self):\n arr = pa.DictionaryArray.from_arrays(\n np.array([0, 0]),\n np.array([5]))\n\n result = arr.to_pandas(zero_copy_only=True)\n values = pd.Categorical([5, 5])\n\n tm.assert_series_equal(pd.Series(result), pd.Series(values),\n check_names=False)\n\n def check_zero_copy_failure(self, arr):\n with pytest.raises(pa.ArrowInvalid):\n arr.to_pandas(zero_copy_only=True)\n\n def test_zero_copy_failure_on_object_types(self):\n self.check_zero_copy_failure(pa.array(['A', 'B', 'C']))\n\n def test_zero_copy_failure_with_int_when_nulls(self):\n self.check_zero_copy_failure(pa.array([0, 1, None]))\n\n def test_zero_copy_failure_with_float_when_nulls(self):\n self.check_zero_copy_failure(pa.array([0.0, 1.0, None]))\n\n def test_zero_copy_failure_on_bool_types(self):\n self.check_zero_copy_failure(pa.array([True, False]))\n\n def test_zero_copy_failure_on_list_types(self):\n arr = pa.array([[1, 2], [8, 9]], type=pa.list_(pa.int64()))\n self.check_zero_copy_failure(arr)\n\n def test_zero_copy_failure_on_timestamp_types(self):\n arr = np.array(['2007-07-13'], dtype='datetime64[ns]')\n self.check_zero_copy_failure(pa.array(arr))\n\n\nclass TestConvertMisc(object):\n \"\"\"\n Miscellaneous conversion tests.\n \"\"\"\n\n type_pairs = [\n (np.int8, pa.int8()),\n (np.int16, pa.int16()),\n (np.int32, pa.int32()),\n (np.int64, pa.int64()),\n (np.uint8, pa.uint8()),\n (np.uint16, pa.uint16()),\n (np.uint32, pa.uint32()),\n (np.uint64, pa.uint64()),\n (np.float16, pa.float16()),\n (np.float32, pa.float32()),\n (np.float64, pa.float64()),\n # XXX unsupported\n # (np.dtype([('a', 'i2')]), pa.struct([pa.field('a', pa.int16())])),\n (np.object, pa.string()),\n (np.object, pa.binary()),\n (np.object, pa.binary(10)),\n (np.object, pa.list_(pa.int64())),\n ]\n\n def test_all_none_objects(self):\n df = pd.DataFrame({'a': [None, None, None]})\n _check_pandas_roundtrip(df)\n\n def test_all_none_category(self):\n df = pd.DataFrame({'a': [None, None, None]})\n df['a'] = df['a'].astype('category')\n _check_pandas_roundtrip(df)\n\n def test_empty_arrays(self):\n for dtype, pa_type in self.type_pairs:\n arr = np.array([], dtype=dtype)\n _check_array_roundtrip(arr, type=pa_type)\n\n def test_threaded_conversion(self):\n df = _alltypes_example()\n _check_pandas_roundtrip(df, use_threads=True)\n _check_pandas_roundtrip(df, use_threads=True, as_batch=True)\n\n def test_category(self):\n repeats = 5\n v1 = ['foo', None, 'bar', 'qux', np.nan]\n v2 = [4, 5, 6, 7, 8]\n v3 = [b'foo', None, b'bar', b'qux', np.nan]\n df = pd.DataFrame({'cat_strings': pd.Categorical(v1 * repeats),\n 'cat_ints': pd.Categorical(v2 * repeats),\n 'cat_binary': pd.Categorical(v3 * repeats),\n 'cat_strings_ordered': pd.Categorical(\n v1 * repeats, categories=['bar', 'qux', 'foo'],\n ordered=True),\n 'ints': v2 * repeats,\n 'ints2': v2 * repeats,\n 'strings': v1 * repeats,\n 'strings2': v1 * repeats,\n 'strings3': v3 * repeats})\n _check_pandas_roundtrip(df)\n\n arrays = [\n pd.Categorical(v1 * repeats),\n pd.Categorical(v2 * repeats),\n pd.Categorical(v3 * repeats)\n ]\n for values in arrays:\n _check_array_roundtrip(values)\n\n def test_empty_category(self):\n # ARROW-2443\n df = pd.DataFrame({'cat': pd.Categorical([])})\n _check_pandas_roundtrip(df)\n\n def test_mixed_types_fails(self):\n data = pd.DataFrame({'a': ['a', 1, 2.0]})\n with pytest.raises(pa.ArrowTypeError):\n pa.Table.from_pandas(data)\n\n data = pd.DataFrame({'a': [1, True]})\n with pytest.raises(pa.ArrowTypeError):\n pa.Table.from_pandas(data)\n\n def test_strided_data_import(self):\n cases = []\n\n columns = ['a', 'b', 'c']\n N, K = 100, 3\n random_numbers = np.random.randn(N, K).copy() * 100\n\n numeric_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',\n 'f4', 'f8']\n\n for type_name in numeric_dtypes:\n cases.append(random_numbers.astype(type_name))\n\n # strings\n cases.append(np.array([tm.rands(10) for i in range(N * K)],\n dtype=object)\n .reshape(N, K).copy())\n\n # booleans\n boolean_objects = (np.array([True, False, True] * N, dtype=object)\n .reshape(N, K).copy())\n\n # add some nulls, so dtype comes back as objects\n boolean_objects[5] = None\n cases.append(boolean_objects)\n\n cases.append(np.arange(\"2016-01-01T00:00:00.001\", N * K,\n dtype='datetime64[ms]')\n .reshape(N, K).copy())\n\n strided_mask = (random_numbers > 0).astype(bool)[:, 0]\n\n for case in cases:\n df = pd.DataFrame(case, columns=columns)\n col = df['a']\n\n _check_pandas_roundtrip(df)\n _check_array_roundtrip(col)\n _check_array_roundtrip(col, mask=strided_mask)\n\n def test_all_nones(self):\n def _check_series(s):\n converted = pa.array(s)\n assert isinstance(converted, pa.NullArray)\n assert len(converted) == 3\n assert converted.null_count == 3\n assert converted[0] is pa.NA\n\n _check_series(pd.Series([None] * 3, dtype=object))\n _check_series(pd.Series([np.nan] * 3, dtype=object))\n _check_series(pd.Series([np.sqrt(-1)] * 3, dtype=object))\n\n def test_partial_schema(self):\n data = OrderedDict([\n ('a', [0, 1, 2, 3, 4]),\n ('b', np.array([-10, -5, 0, 5, 10], dtype=np.int32)),\n ('c', [-10, -5, 0, 5, 10])\n ])\n df = pd.DataFrame(data)\n\n partial_schema = pa.schema([\n pa.field('a', pa.int64()),\n pa.field('b', pa.int32())\n ])\n\n expected_schema = pa.schema([\n pa.field('a', pa.int64()),\n pa.field('b', pa.int32()),\n pa.field('c', pa.int64())\n ])\n\n _check_pandas_roundtrip(df, schema=partial_schema,\n expected_schema=expected_schema)\n\n def test_table_batch_empty_dataframe(self):\n df = pd.DataFrame({})\n _check_pandas_roundtrip(df)\n _check_pandas_roundtrip(df, as_batch=True)\n\n df2 = pd.DataFrame({}, index=[0, 1, 2])\n _check_pandas_roundtrip(df2, preserve_index=True)\n _check_pandas_roundtrip(df2, as_batch=True, preserve_index=True)\n\n def test_convert_empty_table(self):\n arr = pa.array([], type=pa.int64())\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=np.int64))\n arr = pa.array([], type=pa.string())\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n arr = pa.array([], type=pa.list_(pa.int64()))\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n arr = pa.array([], type=pa.struct([pa.field('a', pa.int64())]))\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n\n def test_non_natural_stride(self):\n \"\"\"\n ARROW-2172: converting from a Numpy array with a stride that's\n not a multiple of itemsize.\n \"\"\"\n dtype = np.dtype([('x', np.int32), ('y', np.int16)])\n data = np.array([(42, -1), (-43, 2)], dtype=dtype)\n assert data.strides == (6,)\n arr = pa.array(data['x'], type=pa.int32())\n assert arr.to_pylist() == [42, -43]\n arr = pa.array(data['y'], type=pa.int16())\n assert arr.to_pylist() == [-1, 2]\n\n def test_mixed_integer_columns(self):\n row = [[], []]\n df = pd.DataFrame(data=[row], columns=['foo', 123])\n expected_df = pd.DataFrame(data=[row], columns=['foo', '123'])\n _check_pandas_roundtrip(df, expected=expected_df, preserve_index=True)\n\n\ndef _fully_loaded_dataframe_example():\n from distutils.version import LooseVersion\n\n index = pd.MultiIndex.from_arrays([\n pd.date_range('2000-01-01', periods=5).repeat(2),\n np.tile(np.array(['foo', 'bar'], dtype=object), 5)\n ])\n\n c1 = pd.date_range('2000-01-01', periods=10)\n data = {\n 0: c1,\n 1: c1.tz_localize('utc'),\n 2: c1.tz_localize('US/Eastern'),\n 3: c1[::2].tz_localize('utc').repeat(2).astype('category'),\n 4: ['foo', 'bar'] * 5,\n 5: pd.Series(['foo', 'bar'] * 5).astype('category').values,\n 6: [True, False] * 5,\n 7: np.random.randn(10),\n 8: np.random.randint(0, 100, size=10),\n 9: pd.period_range('2013', periods=10, freq='M')\n }\n\n if LooseVersion(pd.__version__) >= '0.21':\n # There is an issue with pickling IntervalIndex in pandas 0.20.x\n data[10] = pd.interval_range(start=1, freq=1, periods=10)\n\n return pd.DataFrame(data, index=index)\n\n\[email protected]('columns', ([b'foo'], ['foo']))\ndef test_roundtrip_with_bytes_unicode(columns):\n df = pd.DataFrame(columns=columns)\n table1 = pa.Table.from_pandas(df)\n table2 = pa.Table.from_pandas(table1.to_pandas())\n assert table1.equals(table2)\n assert table1.schema.equals(table2.schema)\n assert table1.schema.metadata == table2.schema.metadata\n\n\ndef _check_serialize_components_roundtrip(df):\n ctx = pa.default_serialization_context()\n\n components = ctx.serialize(df).to_components()\n deserialized = ctx.deserialize_components(components)\n\n tm.assert_frame_equal(df, deserialized)\n\n\ndef test_serialize_deserialize_pandas():\n # ARROW-1784, serialize and deserialize DataFrame by decomposing\n # BlockManager\n df = _fully_loaded_dataframe_example()\n _check_serialize_components_roundtrip(df)\n\n\ndef _pytime_from_micros(val):\n microseconds = val % 1000000\n val //= 1000000\n seconds = val % 60\n val //= 60\n minutes = val % 60\n hours = val // 60\n return time(hours, minutes, seconds, microseconds)\n\n\ndef _pytime_to_micros(pytime):\n return (pytime.hour * 3600000000 +\n pytime.minute * 60000000 +\n pytime.second * 1000000 +\n pytime.microsecond)\n" ]
[ [ "pandas.to_datetime", "pandas.Series", "numpy.sqrt", "numpy.random.random_sample", "pandas.DataFrame", "numpy.dtype", "pandas.util.testing.assert_frame_equal", "numpy.random.randn", "numpy.iinfo", "numpy.bool_", "numpy.random.randint", "numpy.testing.assert_equal", "numpy.arange", "pandas.util.testing.assert_series_equal", "pandas.Index", "pandas.DatetimeIndex", "numpy.zeros", "pandas.to_numeric", "pandas.concat", "pandas.interval_range", "numpy.isnan", "pandas.Categorical", "numpy.int64", "pandas.date_range", "numpy.array", "pandas.isnull", "numpy.random.seed", "pandas.period_range", "numpy.int32", "pandas.MultiIndex.from_arrays", "numpy.ones", "numpy.testing.assert_array_equal", "pandas.util.testing.rands", "numpy.float64", "numpy.ma.masked_array", "pandas.Timestamp", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
msenosain/TMA36_dataanalysis
[ "ba390b40e9ffb2bf8ec39b3bd6e8aa000174c313" ]
[ "src/data_integration/pw_corr.py" ]
[ "import pandas as pd\nimport pingouin as pg\n\ndef pw_corr(data_path=\"data/TMA36_project/Radiomics/processed/rad_healthmyne.csv\", \n cde_path=\"data/TMA36_project/CDE/CDE_TMA36_2020FEB25_SA_MF.csv\"):\n rad_hm = pd.read_csv(data_path, index_col=0)\n cde = pd.read_csv(cde_path, index_col=1)\n cde_sila = pd.DataFrame(cde['SILA'])\n rad_hm_sila = pd.merge(rad_hm, cde_sila, how='left', left_index=True, right_index=True)\n pairwise = rad_hm_sila.pairwise_corr(method='spearman',padjust='holm', columns=['SILA'])\n pairwise_sig = pairwise[pairwise['p-corr']<0.05]\n\n return pairwise_sig" ]
[ [ "pandas.merge", "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
kyuhyoung/grasping-invisible
[ "2aaaeb9e28995628ec038a79496453be9f26ffff", "2aaaeb9e28995628ec038a79496453be9f26ffff" ]
[ "utils.py", "policies.py" ]
[ "import math\n\nimport numpy as np\nfrom skimage.morphology.convex_hull import convex_hull_image\nfrom scipy.ndimage.morphology import binary_dilation\n\n\ndef check_grasp_margin(target_mask_heightmap, depth_heightmap):\n margin_mask = binary_dilation(target_mask_heightmap, iterations=10).astype(np.float32)-target_mask_heightmap\n margin_depth = margin_mask * depth_heightmap\n margin_depth[np.isnan(margin_depth)] = 0\n margin_depth[margin_depth > 0.3] = 0\n margin_depth[margin_depth < 0.02] = 0\n margin_depth[margin_depth > 0] = 1\n margin_value = np.sum(margin_depth)\n return margin_value/np.sum(margin_mask), margin_value/np.sum(target_mask_heightmap)\n\n\ndef check_push_target_oriented(best_pix_ind, push_end_pix_yx, target_mask_heightmap, mask_count_threshold=5):\n mask_hull = convex_hull_image(target_mask_heightmap)\n mask_count = 0\n x1 = best_pix_ind[2]\n y1 = best_pix_ind[1]\n x2 = push_end_pix_yx[1]\n y2 = push_end_pix_yx[0]\n x_range = abs(x2-x1)\n y_range = abs(y2-y1)\n if x_range > y_range:\n k = (y2-y1)/(x2-x1)\n b = y1-k*x1\n for x in range(min(int(x1), int(x2)), max(int(x1), int(x2))+1):\n y = int(k*x+b)\n try:\n mask_count += mask_hull[y, x]\n except IndexError:\n pass\n else:\n k = (x2-x1)/(y2-y1)\n b = x1-k*y1\n for y in range(min(int(y1), int(y2)), max(int(y1), int(y2))+1):\n x = int(k*y+b)\n try:\n mask_count += mask_hull[y, x]\n except IndexError:\n pass\n if mask_count > mask_count_threshold:\n return True\n else:\n return False\n\n\ndef check_grasp_target_oriented(best_pix_ind, target_mask_heightmap):\n mask_hull = convex_hull_image(target_mask_heightmap)\n if mask_hull[int(best_pix_ind[1]), int(best_pix_ind[2])]:\n return True\n else:\n return False\n\n\ndef get_push_pix(push_maps, num_rotations):\n push_pix_ind = np.unravel_index(np.argmax(push_maps), push_maps.shape)\n push_end_pix_yx = get_push_end_pix_yx(push_pix_ind, num_rotations)\n return push_pix_ind, push_end_pix_yx\n\n\ndef get_push_end_pix_yx(push_pix_ind, num_rotations):\n push_orientation = [1.0, 0.0]\n push_length_pix = 0.1/0.002\n rotation_angle = np.deg2rad(push_pix_ind[0]*(360.0/num_rotations))\n push_direction = np.asarray([push_orientation[0] * np.cos(rotation_angle) - push_orientation[1] * np.sin(rotation_angle),\n push_orientation[0] * np.sin(rotation_angle) + push_orientation[1] * np.cos(rotation_angle)])\n return [push_pix_ind[1] + push_direction[1] * push_length_pix, push_pix_ind[2] + push_direction[0] * push_length_pix]\n\n\ndef check_env_depth_change(prev_depth_heightmap, depth_heightmap, change_threshold=300):\n depth_diff = abs(prev_depth_heightmap-depth_heightmap)\n depth_diff[np.isnan(depth_diff)] = 0\n depth_diff[depth_diff > 0.3] = 0\n depth_diff[depth_diff < 0.02] = 0\n depth_diff[depth_diff > 0] = 1\n change_value = np.sum(depth_diff)\n change_detected = change_value > change_threshold\n\n return change_detected, change_value\n\n\ndef check_target_depth_change(prev_depth_heightmap, prev_target_mask_heightmap, depth_heightmap, change_threshold=50):\n prev_mask_hull = binary_dilation(convex_hull_image(prev_target_mask_heightmap), iterations=5)\n depth_diff = prev_mask_hull*(prev_depth_heightmap-depth_heightmap)\n depth_diff[np.isnan(depth_diff)] = 0\n depth_diff[depth_diff > 0.3] = 0\n depth_diff[depth_diff < 0.02] = 0\n depth_diff[depth_diff > 0] = 1\n change_value = np.sum(depth_diff)\n change_detected = change_value > change_threshold\n\n return change_detected, change_value\n\n\ndef process_mask_heightmaps(segment_results, seg_mask_heightmaps):\n names = []\n heightmaps = []\n for i in range(len(segment_results['labels'])):\n name = segment_results['labels'][i]\n heightmap = seg_mask_heightmaps[:, :, i]\n if np.sum(heightmap) > 10:\n names.append(name)\n heightmaps.append(heightmap)\n return {'names': names, 'heightmaps': heightmaps}\n\n\ndef get_replay_id(predicted_value_log, label_value_log, reward_value_log, sample_ind, replay_type):\n # Prioritized experience replay, find sample with highest surprise value\n sample_ind = np.asarray(sample_ind)\n predicted_values = np.asarray(predicted_value_log)[sample_ind]\n label_values = np.asarray(label_value_log)[sample_ind]\n reward_values = np.asarray(reward_value_log)[sample_ind]\n if replay_type == 'augment':\n # assume predicted_value for different mask input are close\n label_values = label_values - reward_values + 1.0\n\n sample_surprise_values = np.abs(predicted_values - label_values)\n sorted_surprise_ind = np.argsort(sample_surprise_values[:, 0])\n sorted_sample_ind = sample_ind[sorted_surprise_ind]\n pow_law_exp = 2\n rand_sample_ind = int(np.round(np.random.power(pow_law_exp, 1) * (sample_ind.size - 1)))\n sample_iteration = sorted_sample_ind[rand_sample_ind]\n print(replay_type.capitalize(), 'replay: iteration %d (surprise value: %f)' %\n (sample_iteration, sample_surprise_values[sorted_surprise_ind[rand_sample_ind]]))\n return sample_iteration\n\n\ndef get_pointcloud(color_img, depth_img, masks_imgs, camera_intrinsics):\n\n # Get depth image size\n im_h = depth_img.shape[0]\n im_w = depth_img.shape[1]\n\n # Project depth into 3D point cloud in camera coordinates\n pix_x, pix_y = np.meshgrid(np.linspace(0, im_w-1, im_w), np.linspace(0, im_h-1, im_h))\n cam_pts_x = np.multiply(pix_x-camera_intrinsics[0][2],depth_img/camera_intrinsics[0][0])\n cam_pts_y = np.multiply(pix_y-camera_intrinsics[1][2],depth_img/camera_intrinsics[1][1])\n cam_pts_z = depth_img.copy()\n cam_pts_x.shape = (im_h*im_w, 1)\n cam_pts_y.shape = (im_h*im_w, 1)\n cam_pts_z.shape = (im_h*im_w, 1)\n\n # Reshape image into colors for 3D point cloud\n rgb_pts_r = color_img[:, :, 0]\n rgb_pts_g = color_img[:, :, 1]\n rgb_pts_b = color_img[:, :, 2]\n rgb_pts_r.shape = (im_h*im_w, 1)\n rgb_pts_g.shape = (im_h*im_w, 1)\n rgb_pts_b.shape = (im_h*im_w, 1)\n\n num_masks = masks_imgs.shape[2]\n masks_pts = masks_imgs.copy()\n masks_pts = masks_pts.transpose(2, 0, 1).reshape(num_masks, -1)\n\n cam_pts = np.concatenate((cam_pts_x, cam_pts_y, cam_pts_z), axis=1)\n rgb_pts = np.concatenate((rgb_pts_r, rgb_pts_g, rgb_pts_b), axis=1)\n\n return cam_pts, rgb_pts, masks_pts\n\n\ndef get_heightmap(color_img, depth_img, masks_imgs, cam_intrinsics, cam_pose, workspace_limits, heightmap_resolution):\n\n num_masks = masks_imgs.shape[2]\n\n # Compute heightmap size\n heightmap_size = np.round(((workspace_limits[1][1] - workspace_limits[1][0])/heightmap_resolution, (workspace_limits[0][1] - workspace_limits[0][0])/heightmap_resolution)).astype(int)\n\n # Get 3D point cloud from RGB-D images\n surface_pts, color_pts, masks_pts = get_pointcloud(color_img, depth_img, masks_imgs, cam_intrinsics)\n\n # Transform 3D point cloud from camera coordinates to robot coordinates\n surface_pts = np.transpose(np.dot(cam_pose[0:3,0:3],np.transpose(surface_pts)) + np.tile(cam_pose[0:3,3:],(1,surface_pts.shape[0])))\n\n # Sort surface points by z value\n sort_z_ind = np.argsort(surface_pts[:,2])\n surface_pts = surface_pts[sort_z_ind]\n color_pts = color_pts[sort_z_ind]\n masks_pts = masks_pts[:, sort_z_ind]\n\n # Filter out surface points outside heightmap boundaries\n heightmap_valid_ind = np.logical_and(np.logical_and(np.logical_and(np.logical_and(surface_pts[:,0] >= workspace_limits[0][0], surface_pts[:,0] < workspace_limits[0][1]), surface_pts[:,1] >= workspace_limits[1][0]), surface_pts[:,1] < workspace_limits[1][1]), surface_pts[:,2] < workspace_limits[2][1])\n surface_pts = surface_pts[heightmap_valid_ind]\n color_pts = color_pts[heightmap_valid_ind]\n masks_pts = masks_pts[:, heightmap_valid_ind]\n\n # Create orthographic top-down-view RGB-D heightmaps\n color_heightmap_r = np.zeros((heightmap_size[0], heightmap_size[1], 1), dtype=np.uint8)\n color_heightmap_g = np.zeros((heightmap_size[0], heightmap_size[1], 1), dtype=np.uint8)\n color_heightmap_b = np.zeros((heightmap_size[0], heightmap_size[1], 1), dtype=np.uint8)\n masks_heightmaps = np.zeros((heightmap_size[0], heightmap_size[1], num_masks), dtype=np.uint8)\n depth_heightmap = np.zeros(heightmap_size)\n heightmap_pix_x = np.floor((surface_pts[:,0] - workspace_limits[0][0])/heightmap_resolution).astype(int)\n heightmap_pix_y = np.floor((surface_pts[:,1] - workspace_limits[1][0])/heightmap_resolution).astype(int)\n color_heightmap_r[heightmap_pix_y,heightmap_pix_x] = color_pts[:, [0]]\n color_heightmap_g[heightmap_pix_y,heightmap_pix_x] = color_pts[:, [1]]\n color_heightmap_b[heightmap_pix_y,heightmap_pix_x] = color_pts[:, [2]]\n color_heightmap = np.concatenate((color_heightmap_r, color_heightmap_g, color_heightmap_b), axis=2)\n for c in range(num_masks):\n masks_heightmaps[heightmap_pix_y, heightmap_pix_x, c] = masks_pts[c, :]\n depth_heightmap[heightmap_pix_y, heightmap_pix_x] = surface_pts[:, 2]\n z_bottom = workspace_limits[2][0]\n depth_heightmap = depth_heightmap - z_bottom\n depth_heightmap[depth_heightmap < 0] = 0\n depth_heightmap[depth_heightmap == -z_bottom] = np.nan\n\n return color_heightmap, depth_heightmap, masks_heightmaps\n\n\n# Get rotation matrix from euler angles\ndef euler2rotm(theta):\n R_x = np.array([[1, 0, 0],\n [0, math.cos(theta[0]), -math.sin(theta[0])],\n [0, math.sin(theta[0]), math.cos(theta[0])]])\n R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])],\n [0, 1, 0],\n [-math.sin(theta[1]), 0, math.cos(theta[1])]])\n R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0],\n [math.sin(theta[2]), math.cos(theta[2]), 0],\n [0, 0, 1]])\n R = np.dot(R_z, np.dot(R_y, R_x))\n return R\n", "import os\nimport random\nfrom collections import deque\nfrom collections import namedtuple\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torch\nfrom scipy import signal\nfrom scipy.ndimage.interpolation import shift\n\nTransition = namedtuple('Transition', ('inputs', 'labels'))\n\n\nclass ReplayMemory(object):\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n \"\"\"Saves a transition.\"\"\"\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(*args)\n self.position = (self.position + 1) % self.capacity\n\n def get_data(self):\n transitions = self.memory\n data = Transition(*zip(*transitions))\n return data.inputs, data.labels\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def __len__(self):\n return len(self.memory)\n\n\nclass MLP(nn.Module):\n def __init__(self, in_dim):\n super(MLP, self).__init__()\n self.in_dim = in_dim\n self.bn1 = nn.BatchNorm1d(in_dim)\n self.fc1 = nn.Linear(in_dim, 16)\n self.bn2 = nn.BatchNorm1d(16)\n self.fc2 = nn.Linear(16, 8)\n self.bn3 = nn.BatchNorm1d(8)\n self.fc3 = nn.Linear(8, 2)\n\n def forward(self, x):\n x = F.relu(self.fc1(self.bn1(x)))\n x = F.relu(self.fc2(self.bn2(x)))\n x = self.fc3(self.bn3(x))\n return x\n\n\ndef init_weights(m):\n if type(m) == nn.Linear:\n torch.nn.init.xavier_uniform_(m.weight)\n m.bias.data.fill_(0.01)\n\n\nclass Coordinator(object):\n\n def __init__(self, save_dir, ckpt_file, feat_size=5, buffer_size=200, batch_size=20):\n self.save_dir = save_dir\n self.buffer_size = buffer_size\n self.batch_size = batch_size\n self.memory = ReplayMemory(buffer_size)\n self.net = MLP(in_dim=feat_size)\n self.net.apply(init_weights)\n if ckpt_file is not None:\n self.load_networks(ckpt_file)\n print('Pre-trained coordinator model loaded from: %s' % ckpt_file)\n self.optimizer = torch.optim.SGD(self.net.parameters(), lr=0.001, momentum=0.9)\n self.criterion = nn.CrossEntropyLoss()\n\n def optimize_model(self):\n if len(self.memory) < self.batch_size:\n return None, None\n\n transitions = self.memory.sample(self.batch_size)\n batch = Transition(*zip(*transitions))\n\n self.net.train()\n\n self.optimizer.zero_grad()\n outputs = self.net(torch.tensor(batch.inputs, dtype=torch.float).float())\n labels = torch.tensor(batch.labels).float().flatten().long()\n loss = self.criterion(outputs, labels)\n loss.backward()\n self.optimizer.step()\n\n lc = loss.cpu().detach().numpy()\n acc = self.get_accuracy()\n\n print('Coordinator training loss %f, acc %f' % (lc, acc))\n\n return lc, acc\n\n def predict(self, X):\n self.net.eval()\n net_outputs = self.net(torch.tensor(X, dtype=torch.float).view(-1, self.net.in_dim))\n return np.argmax(net_outputs.view(-1,2).cpu().detach().numpy(), axis=1)\n\n def get_accuracy(self):\n X_val, y_val = self.memory.get_data()\n y_pre = self.predict(X_val)\n accuracy = np.array(y_val == y_pre).mean()\n return accuracy\n\n def save_networks(self, which_epoch):\n save_filename = 'coordinator-%06d.pth' % which_epoch\n save_path = os.path.join(self.save_dir, save_filename)\n torch.save(self.net.cpu().state_dict(), save_path)\n\n def load_networks(self, load_path):\n self.net.load_state_dict(torch.load(load_path))\n\n\ndef gkern(kernlen, std):\n \"\"\"Returns a 2D Gaussian kernel array.\"\"\"\n gkern1d = signal.gaussian(kernlen, std=std).reshape(kernlen, 1)\n gkern2d = np.outer(gkern1d, gkern1d)\n return gkern2d\n\n\nclass Explorer(object):\n\n def __init__(self, map_size, buffer_size=3, prob_scaled=0.75, std=25):\n # assume the map is square, so map_size is a scalar\n # prob_scaled and std is the fine-tuned parameters for our workspace\n\n # compute basic kernel\n gkernel = gkern(kernlen=map_size, std=std)\n self.kcenter = np.array(np.unravel_index(np.argmax(gkernel), gkernel.shape))\n ad_gkernel = (1 - prob_scaled) * gkernel / (np.max(gkernel))\n self.bkernel = 1 - ad_gkernel\n self.ones_kernel = np.ones((map_size, map_size))\n\n # kernel buffer\n self.kbuffer = deque([], buffer_size)\n self.kbuffer.append(self.ones_kernel)\n\n def get_kernel(self, center):\n bkernel_shifted = shift(self.bkernel, np.array(center).reshape(-1)-self.kcenter, cval=1.0)\n return bkernel_shifted\n\n def update(self, prev_act_pos):\n prev_kernel = self.get_kernel(prev_act_pos)\n self.kbuffer.append(self.ones_kernel)\n for i in range(len(self.kbuffer)):\n self.kbuffer[i] = np.multiply(self.kbuffer[i], prev_kernel)\n\n def reset(self):\n self.kbuffer.clear()\n self.kbuffer.append(self.bkernel)\n\n def get_action_maps(self, prior):\n post = np.multiply(prior, self.kbuffer[0])\n return post / np.max(post)\n" ]
[ [ "numpy.dot", "scipy.ndimage.morphology.binary_dilation", "numpy.linspace", "numpy.asarray", "numpy.concatenate", "numpy.round", "numpy.sin", "numpy.argmax", "numpy.zeros", "numpy.random.power", "numpy.multiply", "numpy.isnan", "numpy.deg2rad", "numpy.floor", "numpy.transpose", "numpy.argsort", "numpy.logical_and", "numpy.sum", "numpy.abs", "numpy.tile", "numpy.cos" ], [ "torch.nn.BatchNorm1d", "torch.nn.CrossEntropyLoss", "numpy.multiply", "torch.load", "numpy.ones", "torch.tensor", "torch.nn.Linear", "numpy.max", "numpy.argmax", "torch.nn.init.xavier_uniform_", "numpy.outer", "numpy.array", "scipy.signal.gaussian" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.16", "1.0", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "0.10", "0.17", "1.3" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "1.0", "0.19", "0.18", "0.12", "0.10", "0.17", "0.16" ], "tensorflow": [] } ]
xiebaiyuan/PaddleLite
[ "6f7280a91741d1c63fcb0296ac5c08c4e81c2a90" ]
[ "lite/tests/unittest_py/auto_scan_base.py" ]
[ "# Copyright (c) 2021 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 abc\nimport os\nimport enum\nimport time\nimport logging\nimport shutil\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.initializer import NumpyArrayInitializer\nfrom paddle.fluid.core import PassVersionChecker\nimport paddle.fluid.core as core\nfrom paddle import compat as cpt\nimport paddle.inference as paddle_infer\nfrom typing import Optional, List, Callable, Dict, Any, Set\nfrom program_config import TensorConfig, OpConfig, ProgramConfig, create_fake_model, create_quant_model\n\nfrom itertools import product\nfrom program_config import CxxConfig, TargetType, PrecisionType, DataLayoutType, Place\n\nimport hypothesis\nfrom hypothesis import given, settings, seed\nimport hypothesis.strategies as st\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--target\", choices=['Host', 'X86','CUDA','ARM','OpenCL','FPGA','NPU','MLU','RKNPU','APU','HUAWEI_ASCEND_NPU','INTEL_FPGA'], required=True)\nlogging.basicConfig(level=logging.INFO, format=\"%(message)s\")\n\nsettings.register_profile(\n \"ci\",\n max_examples=10,\n suppress_health_check=hypothesis.HealthCheck.all(),\n deadline=None,\n print_blob=True,\n derandomize=True,\n report_multiple_bugs=False)\nsettings.load_profile(\"ci\")\n\nclass IgnoreReasonsBase(enum.Enum):\n # Paddle not support, but paddlelite support, we need to add the feature.\n PADDLE_NOT_IMPLEMENTED = 0\n # paddlelite not support.\n PADDLELITE_NOT_SUPPORT = 1\n # Accuracy is abnormal after enabling pass.\n ACCURACY_ERROR = 2\n\n\n\nclass AutoScanBaseTest(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n self.valid_places = []\n self.thread_num = [1]\n\n np.random.seed(1024)\n paddle.enable_static()\n super(AutoScanBaseTest, self).__init__(*args, **kwargs)\n self.ignore_cases = []\n abs_dir = os.path.abspath(os.path.dirname(__file__))\n self.cache_dir = os.path.join(abs_dir,\n str(self.__module__) + '_cache_dir')\n self.available_passes_in_framework = set()\n self.num_ran_programs = 0\n self.num_invalid_programs = 0\n self.num_ignore_tests = 0\n self.num_predictor_kinds = 0\n\n args = parser.parse_args()\n self.args = args\n\n\n @abc.abstractmethod\n def sample_program_configs(self, draw):\n '''\n Generate all config with the combination of different Input tensor shape and\n different Attr values.\n '''\n raise NotImplementedError\n\n @abc.abstractmethod\n def sample_predictor_configs(self):\n raise NotImplementedError\n\n @abc.abstractmethod\n def add_ignore_check_case(\n self,\n teller: [Callable[[ProgramConfig, CxxConfig], bool]],\n reason: IgnoreReasonsBase,\n note: str):\n self.ignore_cases.append((teller, reason, note))\n\n @abc.abstractmethod\n def is_program_valid(self, program_config: ProgramConfig, predictor_config: CxxConfig) -> bool:\n return True\n\n def run_test_config(self, model, params, prog_config, pred_config,\n feed_data) -> Dict[str, np.ndarray]:\n '''\n Test a single case.\n '''\n pred_config.set_model_buffer(model, len(model), params, len(params))\n predictor = paddle_infer.create_predictor(pred_config)\n self.available_passes_in_framework = self.available_passes_in_framework | set(\n pred_config.pass_builder().all_passes())\n\n for name, _ in prog_config.inputs.items():\n input_tensor = predictor.get_input_handle(name)\n input_tensor.copy_from_cpu(feed_data[name]['data'])\n if feed_data[name]['lod'] is not None:\n input_tensor.set_lod(feed_data[name]['lod'])\n predictor.run()\n result = {}\n for out_name, o_name in zip(prog_config.outputs,\n predictor.get_output_names()):\n result[out_name] = predictor.get_output_handle(o_name).copy_to_cpu()\n return result\n\n\n @abc.abstractmethod\n def assert_tensors_near(self,\n atol: float,\n rtol: float,\n tensor: Dict[str, np.array],\n baseline: Dict[str, np.array]):\n if len(tensor) == 1 and len(baseline) == 1:\n tensor_key = list(tensor.keys())\n arr = np.array(tensor[tensor_key[0]])\n base_key = list(baseline.keys())\n base = np.array(baseline[base_key[0]])\n self.assertTrue(\n base.shape == arr.shape,\n \"The output shapes are not equal, the baseline shape is \" +\n str(base.shape) + ', but got ' + str(arr.shape))\n self.assertTrue(\n np.allclose(\n base, arr, atol=atol, rtol=rtol),\n \"Output has diff. \")\n else:\n for key in tensor:\n opencl_str = \"/target_trans\"\n index = key.rfind(opencl_str)\n paddlekey=key\n if index > 0:\n paddlekey = key[0: index]\n if (key == \"saved_mean\" or key == \"saved_variance\"):\n # training using data\n continue\n arr = np.array(tensor[key])\n self.assertTrue(\n baseline[paddlekey].shape == arr.shape,\n \"The output shapes are not equal, the baseline shape is \" +\n str(baseline[paddlekey].shape) + ', but got ' + str(arr.shape))\n self.assertTrue(\n np.allclose(\n baseline[paddlekey], arr, atol=atol, rtol=rtol),\n \"Output has diff. \")\n\n def generate_op_config(self,\n ops_config: List[Dict[str, Any]]) -> List[OpConfig]:\n ops = []\n for i in range(len(ops_config)):\n op_config = ops_config[i]\n ops.append(\n OpConfig(\n type=op_config['op_type'],\n inputs=op_config['op_inputs'],\n outputs=op_config['op_outputs'],\n attrs=op_config['op_attrs']))\n return ops\n\n @abc.abstractmethod\n def ignore_log(self, msg: str):\n logging.warning(\"SKIP: \" + msg)\n\n @abc.abstractmethod\n def fail_log(self, msg: str):\n logging.fatal(\"FAILE: \" + msg)\n\n @abc.abstractmethod\n def success_log(self, msg: str):\n logging.info(\"SUCCESS: \" + msg)\n\n @abc.abstractmethod\n def create_inference_config(self,\n passes: Optional[List[str]]=None,\n use_gpu: bool=False,\n use_mkldnn: bool=False,\n ir_optim: Optional[bool]=None):\n config = paddle_infer.Config()\n config.switch_ir_debug(True)\n config.disable_glog_info()\n if ir_optim is not None:\n config.switch_ir_optim(ir_optim)\n if use_gpu:\n config.enable_use_gpu(100, 0)\n if use_mkldnn:\n config.enable_mkldnn()\n if passes is not None:\n config.pass_builder().set_passes(passes)\n self.passes = passes\n return config\n\n def run_test(self, quant=False, prog_configs=None):\n status = True\n\n paddlelite_configs, op_list_, (atol_, rtol_) = self.sample_predictor_configs()\n for prog_config in prog_configs:\n # if program is invalid, we should ignore this cases.\n program_valid_ = False\n for paddlelite_config in paddlelite_configs:\n # judge validity of program\n if self.is_program_valid(prog_config, paddlelite_config):\n program_valid_ = True\n if not program_valid_:\n self.num_invalid_programs += 1\n continue\n\n\n self.num_ran_programs += 1\n model, params = create_fake_model(prog_config)\n if quant:\n model, params = create_quant_model(model, params)\n\n feed_data = {}\n for name, tensor_config in prog_config.inputs.items():\n feed_data[name] = {\n 'data': tensor_config.data,\n 'lod': tensor_config.lod\n }\n results: List[Dict[str, np.ndarray]] = []\n\n # baseline: cpu no ir_optim run\n base_config = self.create_inference_config(ir_optim=False)\n logging.info('[ProgramConfig]: ' + str(prog_config))\n results.append(\n self.run_test_config(model, params, prog_config, base_config,\n feed_data))\n\n\n for paddlelite_config in paddlelite_configs:\n # judge validity of program\n if not self.is_program_valid(prog_config, paddlelite_config):\n continue\n\n self.num_predictor_kinds += 1\n # ignore info\n ignore_flag = False\n pred_config = paddlelite_config.value()\n for ignore_info in self.ignore_cases:\n if ignore_info[0](prog_config, paddlelite_config):\n ignore_flag = True\n self.num_ignore_tests += 1\n if ignore_info[1] == IgnoreReasonsBase.ACCURACY_ERROR:\n self.ignore_log(\"[ACCURACY_ERROR] \" +\n ignore_info[2] + ' ' + ' vs ' + self.\n paddlelite_config_str(pred_config))\n else:\n raise NotImplementedError\n break\n if os.path.exists(self.cache_dir):\n shutil.rmtree(self.cache_dir)\n if not os.path.exists(self.cache_dir):\n os.mkdir(self.cache_dir)\n try:\n result, opt_model_bytes = self.run_lite_config(model, params, feed_data, pred_config)\n results.append(result)\n self.assert_tensors_near(atol_, rtol_, results[-1],\n results[0])\n if not ignore_flag and self.passes is not None:\n self.assert_op_list(opt_model_bytes, op_list_)\n except Exception as e:\n self.fail_log(\n self.paddlelite_config_str(pred_config) +\n '\\033[1;31m \\nERROR INFO: {}\\033[0m'.format(str(e)))\n if not ignore_flag:\n status = False\n continue\n self.success_log('PredictorConfig: ' + self.\n paddlelite_config_str(pred_config))\n self.assertTrue(status)\n\n def inference_config_str(self, config) -> bool:\n dic = {}\n enable_mkldnn = config.mkldnn_enabled()\n dic['use_mkldnn'] = enable_mkldnn\n enable_gpu = config.use_gpu()\n return str(dic)\n\n def paddlelite_config_str(self, config) -> bool:\n return str(config)\n\n # method for ignoring\n def add_ignore_pass_case(self):\n return\n\n # judge if program contain op_list\n def assert_op_list(self, model_bytes, op_list_after_fusion):\n if not self.passes:\n raise ValueError(\n \"In PassAutoScan you should give a valid pass name.\")\n pg = paddle.static.deserialize_program(model_bytes)\n main_block = pg.desc.block(0)\n after_op_list = list()\n for i in range(main_block.op_size()):\n if main_block.op(i).type() in [\"feed\", \"fetch\"]:\n continue\n after_op_list.append(main_block.op(i).type())\n self.assertTrue(\n op_list_after_fusion == after_op_list,\n \"Expected operator list after fusion is {}, but now it's {}\".format(\n op_list_after_fusion, after_op_list), )\n\n\n def run_and_statis(\n self,\n quant=False,\n max_examples=100,\n reproduce=None,\n min_success_num=25,\n max_duration=180,\n passes=None ):\n if os.getenv('HYPOTHESIS_TEST_PROFILE', 'ci') == \"dev\":\n max_examples *= 10\n min_success_num *= 10\n # while at ce phase, there's no limit on time\n max_duration = -1\n start_time = time.time()\n settings.register_profile(\n \"ci\",\n max_examples=max_examples,\n suppress_health_check=hypothesis.HealthCheck.all(),\n deadline=None,\n print_blob=True,\n derandomize=True,\n report_multiple_bugs=False, )\n settings.load_profile(\"ci\")\n\n self.passes = passes\n self.add_ignore_pass_case()\n\n def program_generator(draw):\n return self.sample_program_configs(draw)\n\n def run_test(prog_config):\n return self.run_test(quant=quant, prog_configs=[prog_config])\n\n # if current unittest is not active on the input target, we will exit directly.\n if not self.is_actived():\n logging.info(\"Error: This test is not actived on \" + self.get_target())\n return\n\n generator = st.composite(program_generator)\n loop_func = given(generator())(run_test)\n if reproduce is not None:\n loop_func = reproduce(loop_func)\n logging.info(\"Start to running test of {}\".format(type(self)))\n loop_func()\n logging.info(\n \"===================Statistical Information===================\")\n logging.info(\"Number of Generated Programs: {}\".format(\n self.num_ran_programs + self.num_invalid_programs))\n logging.info(\"Number of Invalid Programs: {}\".format(\n self.num_invalid_programs))\n logging.info(\"Number of Ran Programs: {}\".format(self.num_ran_programs))\n logging.info(\"Number of Ignored Tests: {}\".format(\n self.num_ignore_tests))\n if self.num_predictor_kinds == 0:\n successful_ran_programs = int(self.num_ran_programs)\n min_success_num = 0\n else:\n successful_ran_programs = int(self.num_ran_programs -\n self.num_ignore_tests /\n self.num_predictor_kinds)\n\n logging.info(\n \"Number of successfully ran programs approximately equal to {}\".\n format(successful_ran_programs))\n if successful_ran_programs < min_success_num:\n logging.warning(\n \"satisfied_programs = ran_programs - num_ignore_tests / num_predictor_kinds\"\n )\n logging.fatal(\n \"At least {} programs need to ran successfully, but now only about {} programs satisfied.\".\n format(min_success_num, successful_ran_programs))\n assert False\n used_time = time.time() - start_time\n if max_duration > 0 and used_time > max_duration:\n logging.fatal(\n \"The duration exceeds {} seconds, if this is neccessary, try to set a larger number for parameter `max_duration`.\".\n format(max_duration))\n assert False\n\n @abc.abstractmethod\n def run_lite_config(self, model, params, feed_data, pred_config) -> Dict[str, np.ndarray]:\n raise NotImplementedError\n\n\n # enable a predictor config\n # configs will be generated automatically according to inputs\n def enable_testing_on_place(self, target=None, precision=None, layout=None, thread=None, places=None) -> None:\n # set thread_num\n if isinstance(thread,list):\n self.thread_num = list(set(self.thread_num + thread))\n if isinstance(thread,int):\n self.thread_num.append(thread)\n self.thread_num = list(self.thread_num)\n\n # if list[Place] is inputed, this will be used directly\n if places is not None:\n assert isinstance(places, list)\n self.valid_places.append(places)\n return\n # otherwise we will generate a list[Place] from the inputed[target\\precision\\layout]\n assert (target is not None)\n target_ = target if isinstance(target,list) else [target]\n precision_ = precision if isinstance(precision, list) else [precision]\n layout_ = layout if isinstance(layout,list) else [layout]\n for tar_, pre_, lay_ in product(target_, precision_, layout_):\n self.valid_places.append([Place(tar_, pre_, lay_)])\n return\n\n\n def get_target(self) -> str:\n return self.args.target\n\n\n def is_actived(self) -> bool:\n for valid_place_ in self.valid_places:\n if self.get_target() in valid_place_[0]:\n return True\n return False\n\n def get_predictor_configs(self) -> List[CxxConfig]:\n return self.target_to_predictor_configs(self, self.get_target())\n\n # get valid test configs\n @staticmethod\n def target_to_predictor_configs(self,target:str) -> List[CxxConfig]:\n configs_ = []\n for elem_ in self.valid_places:\n if target in elem_[0]:\n for thread_ in self.thread_num:\n config_ = CxxConfig()\n config_.set_valid_places(elem_)\n config_.set_threads(thread_)\n configs_.append(config_)\n return configs_\n" ]
[ [ "numpy.array", "numpy.allclose", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jdehotin/TensorFlow
[ "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "314d9cd9b607460f8bfea80fc828b1521ca18443", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022", "314d9cd9b607460f8bfea80fc828b1521ca18443", "314d9cd9b607460f8bfea80fc828b1521ca18443", "a6c5f8e4e013e54fed8dfcf49fb6de365f018022" ]
[ "tensorflow/python/summary/impl/io_wrapper.py", "tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py", "tensorflow/contrib/slim/python/slim/evaluation_test.py", "tensorflow/contrib/layers/python/layers/feature_column_ops_test.py", "tensorflow/python/client/session_test.py", "tensorflow/contrib/distributions/python/kernel_tests/quantized_distribution_test.py", "tensorflow/contrib/cudnn_rnn/python/kernel_tests/cudnn_rnn_ops_test.py", "tensorflow/contrib/framework/python/ops/prettyprint_ops_test.py", "tensorflow/python/training/ftrl_test.py", "tensorflow/python/kernel_tests/trace_op_test.py", "tensorflow/contrib/layers/python/layers/summaries.py", "tensorflow/python/tools/optimize_for_inference_lib.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# ==============================================================================\n\"\"\"Functions that wrap both gfile and gcs.\n\nThis module is *not* intended to be a general-purpose IO wrapper library; it\nonly implements the operations that are necessary for loading event files. The\nfunctions either dispatch to the gcs library or to gfile, depending on whether\nthe path is a GCS 'pseudo-path' (i.e., it satisfies gcs.IsGCSPath) or not.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.summary.impl import event_file_loader\nfrom tensorflow.python.summary.impl import gcs\nfrom tensorflow.python.summary.impl import gcs_file_loader\n\n\ndef CreateFileLoader(path):\n \"\"\"Creates a file loader for the given path.\n\n Args:\n path: A string representing either a normal path or a GCS\n Returns:\n An object with a Load() method that yields event_pb2.Event protos.\n \"\"\"\n if gcs.IsGCSPath(path):\n return gcs_file_loader.GCSFileLoader(path)\n else:\n return event_file_loader.EventFileLoader(path)\n\n\ndef ListDirectoryAbsolute(directory):\n \"\"\"Yields all files in the given directory. The paths are absolute.\"\"\"\n if gcs.IsGCSPath(directory):\n return gcs.ListDirectory(directory)\n else:\n return (os.path.join(directory, path)\n for path in gfile.ListDirectory(directory))\n\n\ndef ListRecursively(top):\n \"\"\"Walks a directory tree, yielding (dir_path, file_paths) tuples.\n\n For each of `top` and its subdirectories, yields a tuple containing the path\n to the directory and the path to each of the contained files. Note that\n unlike os.Walk()/gfile.Walk(), this does not list subdirectories and the file\n paths are all absolute.\n\n If the directory does not exist, this yields nothing.\n\n Args:\n top: A path to a directory..\n Yields:\n A list of (dir_path, file_paths) tuples.\n \"\"\"\n if gcs.IsGCSPath(top):\n for x in gcs.ListRecursively(top):\n yield x\n else:\n for dir_path, _, filenames in gfile.Walk(top):\n yield (dir_path, (os.path.join(dir_path, filename)\n for filename in filenames))\n\n\ndef IsDirectory(path):\n \"\"\"Returns true if path exists and is a directory.\"\"\"\n if gcs.IsGCSPath(path):\n return gcs.IsDirectory(path)\n else:\n return gfile.IsDirectory(path)\n\n\ndef Exists(path):\n if gcs.IsGCSPath(path):\n return gcs.Exists(path)\n else:\n return gfile.Exists(path)\n\n\ndef Size(path):\n \"\"\"Returns the number of bytes in the given file. Doesn't work on GCS.\"\"\"\n if gcs.IsGCSPath(path):\n raise NotImplementedError(\"io_wrapper.Size doesn't support GCS paths\")\n else:\n return gfile.Open(path).size()\n", "# Copyright 2016 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\"\"\"The Dirichlet Multinomial distribution class.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.distributions.python.ops import distribution\nfrom tensorflow.contrib.distributions.python.ops import distribution_util\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import special_math_ops\n\n\nclass DirichletMultinomial(distribution.Distribution):\n \"\"\"DirichletMultinomial mixture distribution.\n\n This distribution is parameterized by a vector `alpha` of concentration\n parameters for `k` classes and `n`, the counts per each class..\n\n #### Mathematical details\n\n The Dirichlet Multinomial is a distribution over k-class count data, meaning\n for each k-tuple of non-negative integer `counts = [c_1,...,c_k]`, we have a\n probability of these draws being made from the distribution. The distribution\n has hyperparameters `alpha = (alpha_1,...,alpha_k)`, and probability mass\n function (pmf):\n\n ```pmf(counts) = N! / (n_1!...n_k!) * Beta(alpha + c) / Beta(alpha)```\n\n where above `N = sum_j n_j`, `N!` is `N` factorial, and\n `Beta(x) = prod_j Gamma(x_j) / Gamma(sum_j x_j)` is the multivariate beta\n function.\n\n This is a mixture distribution in that `M` samples can be produced by:\n 1. Choose class probabilities `p = (p_1,...,p_k) ~ Dir(alpha)`\n 2. Draw integers `m = (n_1,...,n_k) ~ Multinomial(N, p)`\n\n This class provides methods to create indexed batches of Dirichlet\n Multinomial distributions. If the provided `alpha` is rank 2 or higher, for\n every fixed set of leading dimensions, the last dimension represents one\n single Dirichlet Multinomial distribution. When calling distribution\n functions (e.g. `dist.pmf(counts)`), `alpha` and `counts` are broadcast to the\n same shape (if possible). In all cases, the last dimension of alpha/counts\n represents single Dirichlet Multinomial distributions.\n\n #### Examples\n\n ```python\n alpha = [1, 2, 3]\n n = 2\n dist = DirichletMultinomial(n, alpha)\n ```\n\n Creates a 3-class distribution, with the 3rd class is most likely to be drawn.\n The distribution functions can be evaluated on counts.\n\n ```python\n # counts same shape as alpha.\n counts = [0, 0, 2]\n dist.pmf(counts) # Shape []\n\n # alpha will be broadcast to [[1, 2, 3], [1, 2, 3]] to match counts.\n counts = [[1, 1, 0], [1, 0, 1]]\n dist.pmf(counts) # Shape [2]\n\n # alpha will be broadcast to shape [5, 7, 3] to match counts.\n counts = [[...]] # Shape [5, 7, 3]\n dist.pmf(counts) # Shape [5, 7]\n ```\n\n Creates a 2-batch of 3-class distributions.\n\n ```python\n alpha = [[1, 2, 3], [4, 5, 6]] # Shape [2, 3]\n n = [3, 3]\n dist = DirichletMultinomial(n, alpha)\n\n # counts will be broadcast to [[2, 1, 0], [2, 1, 0]] to match alpha.\n counts = [2, 1, 0]\n dist.pmf(counts) # Shape [2]\n ```\n\n \"\"\"\n\n # TODO(b/27419586) Change docstring for dtype of alpha once int allowed.\n def __init__(self,\n n,\n alpha,\n validate_args=False,\n allow_nan_stats=True,\n name=\"DirichletMultinomial\"):\n \"\"\"Initialize a batch of DirichletMultinomial distributions.\n\n Args:\n n: Non-negative floating point tensor, whose dtype is the same as\n `alpha`. The shape is broadcastable to `[N1,..., Nm]` with `m >= 0`.\n Defines this as a batch of `N1 x ... x Nm` different Dirichlet\n multinomial distributions. Its components should be equal to integer\n values.\n alpha: Positive floating point tensor, whose dtype is the same as\n `n` with shape broadcastable to `[N1,..., Nm, k]` `m >= 0`. Defines\n this as a batch of `N1 x ... x Nm` different `k` class Dirichlet\n multinomial distributions.\n validate_args: `Boolean`, default `False`. Whether to assert valid\n values for parameters `alpha` and `n`, and `x` in `prob` and\n `log_prob`. If `False`, correct behavior is not guaranteed.\n allow_nan_stats: `Boolean`, default `True`. If `False`, raise an\n exception if a statistic (e.g. mean/mode/etc...) is undefined for any\n batch member. If `True`, batch members with valid parameters leading to\n undefined statistics will return NaN for this statistic.\n name: The name to prefix Ops created by this distribution class.\n\n Examples:\n\n ```python\n # Define 1-batch of 2-class Dirichlet multinomial distribution,\n # also known as a beta-binomial.\n dist = DirichletMultinomial(2.0, [1.1, 2.0])\n\n # Define a 2-batch of 3-class distributions.\n dist = DirichletMultinomial([3., 4], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n ```\n\n \"\"\"\n with ops.name_scope(name, values=[n, alpha]) as ns:\n # Broadcasting works because:\n # * The broadcasting convention is to prepend dimensions of size [1], and\n # we use the last dimension for the distribution, wherease\n # the batch dimensions are the leading dimensions, which forces the\n # distribution dimension to be defined explicitly (i.e. it cannot be\n # created automatically by prepending). This forces enough\n # explicitivity.\n # * All calls involving `counts` eventually require a broadcast between\n # `counts` and alpha.\n self._alpha = self._assert_valid_alpha(alpha, validate_args)\n self._n = self._assert_valid_n(n, validate_args)\n self._alpha_sum = math_ops.reduce_sum(\n self._alpha, reduction_indices=[-1], keep_dims=False)\n super(DirichletMultinomial, self).__init__(\n dtype=self._alpha.dtype,\n parameters={\"alpha\": self._alpha,\n \"alpha_sum\": self._alpha_sum,\n \"n\": self._n},\n is_continuous=False,\n is_reparameterized=False,\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n name=ns)\n\n @property\n def n(self):\n \"\"\"Parameter defining this distribution.\"\"\"\n return self._n\n\n @property\n def alpha(self):\n \"\"\"Parameter defining this distribution.\"\"\"\n return self._alpha\n\n @property\n def alpha_sum(self):\n \"\"\"Summation of alpha parameter.\"\"\"\n return self._alpha_sum\n\n def _batch_shape(self):\n return array_ops.shape(self.alpha_sum)\n\n def _get_batch_shape(self):\n return self.alpha_sum.get_shape()\n\n def _event_shape(self):\n return array_ops.reverse(array_ops.shape(self.alpha), [True])[0]\n\n def _get_event_shape(self):\n # Event shape depends only on alpha, not \"n\".\n return self.alpha.get_shape().with_rank_at_least(1)[-1:]\n\n def _log_prob(self, counts):\n counts = self._assert_valid_counts(counts)\n ordered_prob = (special_math_ops.lbeta(self.alpha + counts) -\n special_math_ops.lbeta(self.alpha))\n log_prob = ordered_prob + distribution_util.log_combinations(\n self.n, counts)\n return log_prob\n\n def _prob(self, counts):\n return math_ops.exp(self._log_prob(counts))\n\n def _mean(self):\n normalized_alpha = self.alpha / array_ops.expand_dims(self.alpha_sum, -1)\n return array_ops.expand_dims(self.n, -1) * normalized_alpha\n\n def _variance(self):\n alpha_sum = array_ops.expand_dims(self.alpha_sum, -1)\n normalized_alpha = self.alpha / alpha_sum\n variance = -math_ops.batch_matmul(\n array_ops.expand_dims(normalized_alpha, -1),\n array_ops.expand_dims(normalized_alpha, -2))\n variance = array_ops.matrix_set_diag(variance, normalized_alpha *\n (1. - normalized_alpha))\n shared_factor = (self.n * (alpha_sum + self.n) /\n (alpha_sum + 1) * array_ops.ones_like(self.alpha))\n variance *= array_ops.expand_dims(shared_factor, -1)\n return variance\n\n def _assert_valid_counts(self, counts):\n \"\"\"Check counts for proper shape, values, then return tensor version.\"\"\"\n counts = ops.convert_to_tensor(counts, name=\"counts\")\n if not self.validate_args:\n return counts\n candidate_n = math_ops.reduce_sum(counts, reduction_indices=[-1])\n return control_flow_ops.with_dependencies([\n check_ops.assert_non_negative(counts),\n check_ops.assert_equal(\n self._n, candidate_n,\n message=\"counts do not sum to n\"),\n distribution_util.assert_integer_form(counts)], counts)\n\n def _assert_valid_alpha(self, alpha, validate_args):\n alpha = ops.convert_to_tensor(alpha, name=\"alpha\")\n if not validate_args:\n return alpha\n return control_flow_ops.with_dependencies(\n [check_ops.assert_rank_at_least(alpha, 1),\n check_ops.assert_positive(alpha)], alpha)\n\n def _assert_valid_n(self, n, validate_args):\n n = ops.convert_to_tensor(n, name=\"n\")\n if not validate_args:\n return n\n return control_flow_ops.with_dependencies(\n [check_ops.assert_non_negative(n),\n distribution_util.assert_integer_form(n)], n)\n\n\n_prob_note = \"\"\"\n\n For each batch of counts `[n_1,...,n_k]`, `P[counts]` is the probability\n that after sampling `n` draws from this Dirichlet Multinomial\n distribution, the number of draws falling in class `j` is `n_j`. Note that\n different sequences of draws can result in the same counts, thus the\n probability includes a combinatorial coefficient.\n\n Note that input, \"counts\", must be a non-negative tensor with dtype `dtype`\n and whose shape can be broadcast with `self.alpha`. For fixed leading\n dimensions, the last dimension represents counts for the corresponding\n Dirichlet Multinomial distribution in `self.alpha`. `counts` is only legal if\n it sums up to `n` and its components are equal to integer values.\n\"\"\"\ndistribution_util.append_class_fun_doc(DirichletMultinomial.log_prob,\n doc_str=_prob_note)\ndistribution_util.append_class_fun_doc(DirichletMultinomial.prob,\n doc_str=_prob_note)\n\ndistribution_util.append_class_fun_doc(DirichletMultinomial.variance,\n doc_str=\"\"\"\n\n The variance for each batch member is defined as the following:\n\n ```\n Var(X_j) = n * alpha_j / alpha_0 * (1 - alpha_j / alpha_0) *\n (n + alpha_0) / (1 + alpha_0)\n ```\n\n where `alpha_0 = sum_j alpha_j`.\n\n The covariance between elements in a batch is defined as:\n\n ```\n Cov(X_i, X_j) = -n * alpha_i * alpha_j / alpha_0 ** 2 *\n (n + alpha_0) / (1 + alpha_0)\n ```\n\n\"\"\")\n", "# Copyright 2016 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\"\"\"Tests for slim.evaluation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nimport glob\nimport os\nimport time\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.platform import flags\nfrom tensorflow.python.platform import gfile\n\nslim = tf.contrib.slim\n\nFLAGS = flags.FLAGS\n\n\ndef GenerateTestData(num_classes, batch_size):\n inputs = np.random.rand(batch_size, num_classes)\n\n np.random.seed(0)\n labels = np.random.randint(low=0, high=num_classes, size=batch_size)\n labels = labels.reshape((batch_size,))\n return inputs, labels\n\n\ndef TestModel(inputs):\n scale = tf.Variable(1.0, trainable=False)\n\n # Scaling the outputs wont change the result...\n outputs = tf.mul(inputs, scale)\n return tf.argmax(outputs, 1), scale\n\n\ndef GroundTruthAccuracy(inputs, labels, batch_size):\n predictions = np.argmax(inputs, 1)\n num_correct = np.sum(predictions == labels)\n return float(num_correct) / batch_size\n\n\nclass EvaluationTest(tf.test.TestCase):\n\n def setUp(self):\n super(EvaluationTest, self).setUp()\n\n num_classes = 8\n batch_size = 16\n inputs, labels = GenerateTestData(num_classes, batch_size)\n self._expected_accuracy = GroundTruthAccuracy(inputs, labels, batch_size)\n\n self._global_step = slim.get_or_create_global_step()\n self._inputs = tf.constant(inputs, dtype=tf.float32)\n self._labels = tf.constant(labels, dtype=tf.int64)\n self._predictions, self._scale = TestModel(self._inputs)\n\n def testUpdateOpsAreEvaluated(self):\n accuracy, update_op = slim.metrics.streaming_accuracy(\n self._predictions, self._labels)\n initial_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n\n with self.test_session() as sess:\n slim.evaluation.evaluation(\n sess, initial_op=initial_op, eval_op=update_op)\n self.assertAlmostEqual(accuracy.eval(), self._expected_accuracy)\n\n def testFinalOpsIsEvaluated(self):\n _, update_op = slim.metrics.streaming_accuracy(\n self._predictions, self._labels)\n initial_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n\n with self.test_session() as sess:\n accuracy_value = slim.evaluation.evaluation(\n sess, initial_op=initial_op, final_op=update_op)\n self.assertAlmostEqual(accuracy_value, self._expected_accuracy)\n\n def testFinalOpsOnEvaluationLoop(self):\n value_op, update_op = slim.metrics.streaming_accuracy(\n self._predictions, self._labels)\n init_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n # Create Checkpoint and log directories\n chkpt_dir = os.path.join(self.get_temp_dir(), 'tmp_logs/')\n gfile.MakeDirs(chkpt_dir)\n logdir = os.path.join(self.get_temp_dir(), 'tmp_logs2/')\n gfile.MakeDirs(logdir)\n\n # Save initialized variables to checkpoint directory\n saver = tf.train.Saver()\n with self.test_session() as sess:\n init_op.run()\n saver.save(sess, os.path.join(chkpt_dir, 'chkpt'))\n\n # Now, run the evaluation loop:\n accuracy_value = slim.evaluation.evaluation_loop(\n '', chkpt_dir, logdir, eval_op=update_op, final_op=value_op,\n max_number_of_evaluations=1)\n self.assertAlmostEqual(accuracy_value, self._expected_accuracy)\n\n def _create_names_to_metrics(self, predictions, labels):\n accuracy0, update_op0 = tf.contrib.metrics.streaming_accuracy(\n predictions, labels)\n accuracy1, update_op1 = tf.contrib.metrics.streaming_accuracy(\n predictions+1, labels)\n\n names_to_values = {'Accuracy': accuracy0, 'Another accuracy': accuracy1}\n names_to_updates = {'Accuracy': update_op0, 'Another accuracy': update_op1}\n return names_to_values, names_to_updates\n\n def _verify_summaries(self, output_dir, names_to_values):\n \"\"\"Verifies that the given `names_to_values` are found in the summaries.\n\n Args:\n output_dir: An existing directory where summaries are found.\n names_to_values: A dictionary of strings to values.\n \"\"\"\n # Check that the results were saved. The events file may have additional\n # entries, e.g. the event version stamp, so have to parse things a bit.\n output_filepath = glob.glob(os.path.join(output_dir, '*'))\n self.assertEqual(len(output_filepath), 1)\n\n events = tf.train.summary_iterator(output_filepath[0])\n summaries = [e.summary for e in events if e.summary.value]\n values = []\n for summary in summaries:\n for value in summary.value:\n values.append(value)\n saved_results = {v.tag: v.simple_value for v in values}\n for name in names_to_values:\n self.assertAlmostEqual(names_to_values[name], saved_results[name])\n\n def testSummariesAreFlushedToDisk(self):\n output_dir = os.path.join(self.get_temp_dir(), 'flush_test')\n if tf.gfile.Exists(output_dir): # For running on jenkins.\n tf.gfile.DeleteRecursively(output_dir)\n\n names_to_metrics, names_to_updates = self._create_names_to_metrics(\n self._predictions, self._labels)\n\n for k in names_to_metrics:\n v = names_to_metrics[k]\n tf.scalar_summary(k, v)\n\n summary_writer = tf.train.SummaryWriter(output_dir)\n\n initial_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n eval_op = tf.group(*names_to_updates.values())\n\n with self.test_session() as sess:\n slim.evaluation.evaluation(\n sess,\n initial_op=initial_op,\n eval_op=eval_op,\n summary_op=tf.merge_all_summaries(),\n summary_writer=summary_writer,\n global_step=self._global_step)\n\n names_to_values = {name: names_to_metrics[name].eval()\n for name in names_to_metrics}\n self._verify_summaries(output_dir, names_to_values)\n\n def testSummariesAreFlushedToDiskWithoutGlobalStep(self):\n output_dir = os.path.join(self.get_temp_dir(), 'flush_test_no_global_step')\n if tf.gfile.Exists(output_dir): # For running on jenkins.\n tf.gfile.DeleteRecursively(output_dir)\n\n names_to_metrics, names_to_updates = self._create_names_to_metrics(\n self._predictions, self._labels)\n\n for k in names_to_metrics:\n v = names_to_metrics[k]\n tf.scalar_summary(k, v)\n\n summary_writer = tf.train.SummaryWriter(output_dir)\n\n initial_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n eval_op = tf.group(*names_to_updates.values())\n\n with self.test_session() as sess:\n slim.evaluation.evaluation(\n sess,\n initial_op=initial_op,\n eval_op=eval_op,\n summary_op=tf.merge_all_summaries(),\n summary_writer=summary_writer)\n\n names_to_values = {name: names_to_metrics[name].eval()\n for name in names_to_metrics}\n self._verify_summaries(output_dir, names_to_values)\n\n def testWithFeedDict(self):\n accuracy, update_op = slim.metrics.streaming_accuracy(\n self._predictions, self._labels)\n initial_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n\n with self.test_session() as sess:\n slim.evaluation.evaluation(\n sess,\n initial_op=initial_op,\n eval_op=update_op,\n eval_op_feed_dict={self._scale: np.ones([], dtype=np.float32)})\n self.assertAlmostEqual(accuracy.eval(), self._expected_accuracy)\n\n def testWithQueueRunning(self):\n strings = ['the', 'cat', 'in', 'the', 'hat']\n _ = tf.train.string_input_producer(strings, capacity=5)\n\n accuracy, update_op = slim.metrics.streaming_accuracy(\n self._predictions, self._labels)\n\n initial_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n\n with self.test_session() as sess:\n slim.evaluation.evaluation(\n sess, initial_op=initial_op, eval_op=update_op)\n self.assertAlmostEqual(accuracy.eval(), self._expected_accuracy)\n\n def testLatestCheckpointReturnsNoneAfterTimeout(self):\n start = time.time()\n ret = slim.evaluation.wait_for_new_checkpoint(\n '/non-existent-dir', 'foo', timeout=1.0, seconds_to_sleep=0.5)\n end = time.time()\n self.assertIsNone(ret)\n # We've waited one time.\n self.assertGreater(end, start + 0.5)\n # The timeout kicked in.\n self.assertLess(end, start + 1.1)\n\n def testMonitorCheckpointsLoopTimeout(self):\n ret = list(slim.evaluation.checkpoints_iterator(\n '/non-existent-dir', timeout=0))\n self.assertEqual(ret, [])\n\n\nclass SingleEvaluationTest(tf.test.TestCase):\n\n def setUp(self):\n super(SingleEvaluationTest, self).setUp()\n\n num_classes = 8\n batch_size = 16\n inputs, labels = GenerateTestData(num_classes, batch_size)\n self._expected_accuracy = GroundTruthAccuracy(inputs, labels, batch_size)\n\n self._global_step = slim.get_or_create_global_step()\n self._inputs = tf.constant(inputs, dtype=tf.float32)\n self._labels = tf.constant(labels, dtype=tf.int64)\n self._predictions, self._scale = TestModel(self._inputs)\n\n def testErrorRaisedIfCheckpointDoesntExist(self):\n checkpoint_path = os.path.join(self.get_temp_dir(),\n 'this_file_doesnt_exist')\n log_dir = os.path.join(self.get_temp_dir(), 'error_raised')\n with self.assertRaises(ValueError):\n slim.evaluation.evaluate_once('', checkpoint_path, log_dir)\n\n def testRestoredModelPerformance(self):\n checkpoint_path = os.path.join(self.get_temp_dir(), 'model.ckpt')\n log_dir = os.path.join(self.get_temp_dir(), 'log_dir1/')\n\n # First, save out the current model to a checkpoint:\n init_op = tf.group(tf.initialize_all_variables(),\n tf.initialize_local_variables())\n saver = tf.train.Saver()\n with self.test_session() as sess:\n sess.run(init_op)\n saver.save(sess, checkpoint_path)\n\n # Next, determine the metric to evaluate:\n value_op, update_op = slim.metrics.streaming_accuracy(\n self._predictions, self._labels)\n\n # Run the evaluation and verify the results:\n accuracy_value = slim.evaluation.evaluate_once(\n '',\n checkpoint_path,\n log_dir,\n eval_op=update_op,\n final_op=value_op)\n self.assertAlmostEqual(accuracy_value, self._expected_accuracy)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# 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# ==============================================================================\n\"\"\"Tests for layers.feature_column_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.contrib.layers.python.layers import feature_column_ops\nfrom tensorflow.python.ops import init_ops\n\n\nclass TransformerTest(tf.test.TestCase):\n\n def testRealValuedColumnIsIdentityTransformation(self):\n real_valued = tf.contrib.layers.real_valued_column(\"price\")\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n output = feature_column_ops._Transformer(features).transform(real_valued)\n with self.test_session():\n self.assertAllEqual(output.eval(), [[20.], [110], [-3]])\n\n def testBucketizedColumn(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n output = feature_column_ops._Transformer(features).transform(bucket)\n with self.test_session():\n self.assertAllEqual(output.eval(), [[2], [3], [0]])\n\n def testBucketizedColumnWithMultiDimensions(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", 2),\n boundaries=[0., 10., 100.])\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20., 110], [110., 20], [-3, -3]])}\n output = feature_column_ops._Transformer(features).transform(bucket)\n with self.test_session():\n self.assertAllEqual(output.eval(), [[2, 3], [3, 2], [0, 0]])\n\n def testCachedTransformation(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n transformer = feature_column_ops._Transformer(features)\n with self.test_session() as sess:\n transformer.transform(bucket)\n num_of_ops = len(sess.graph.get_operations())\n # Verify that the second call to transform the same feature\n # doesn't increase the number of ops.\n transformer.transform(bucket)\n self.assertEqual(num_of_ops, len(sess.graph.get_operations()))\n\n def testSparseColumnWithHashBucket(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n output = feature_column_ops._Transformer(features).transform(hashed_sparse)\n with self.test_session():\n self.assertEqual(output.values.dtype, tf.int64)\n self.assertTrue(all(x < 10 and x >= 0 for x in output.values.eval()))\n self.assertAllEqual(output.indices.eval(), wire_tensor.indices.eval())\n self.assertAllEqual(output.shape.eval(), wire_tensor.shape.eval())\n\n def testSparseIntColumnWithHashBucket(self):\n \"\"\"Tests a sparse column with int values.\"\"\"\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"wire\", 10, dtype=tf.int64)\n wire_tensor = tf.SparseTensor(values=[101, 201, 301],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n output = feature_column_ops._Transformer(features).transform(hashed_sparse)\n with self.test_session():\n self.assertEqual(output.values.dtype, tf.int64)\n self.assertTrue(all(x < 10 and x >= 0 for x in output.values.eval()))\n self.assertAllEqual(output.indices.eval(), wire_tensor.indices.eval())\n self.assertAllEqual(output.shape.eval(), wire_tensor.shape.eval())\n\n def testEmbeddingColumn(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n output = feature_column_ops._Transformer(features).transform(\n tf.contrib.layers.embedding_column(hashed_sparse, 10))\n expected = feature_column_ops._Transformer(features).transform(\n hashed_sparse)\n with self.test_session():\n self.assertAllEqual(output.values.eval(), expected.values.eval())\n self.assertAllEqual(output.indices.eval(), expected.indices.eval())\n self.assertAllEqual(output.shape.eval(), expected.shape.eval())\n\n def testSparseColumnWithKeys(self):\n keys_sparse = tf.contrib.layers.sparse_column_with_keys(\n \"wire\", [\"marlo\", \"omar\", \"stringer\"])\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n output = feature_column_ops._Transformer(features).transform(keys_sparse)\n with self.test_session():\n tf.initialize_all_tables().run()\n self.assertEqual(output.values.dtype, tf.int64)\n self.assertAllEqual(output.values.eval(), [1, 2, 0])\n self.assertAllEqual(output.indices.eval(), wire_tensor.indices.eval())\n self.assertAllEqual(output.shape.eval(), wire_tensor.shape.eval())\n\n def testSparseColumnWithHashBucket_IsIntegerized(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_integerized_feature(\n \"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[100, 1, 25],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n output = feature_column_ops._Transformer(features).transform(hashed_sparse)\n with self.test_session():\n self.assertEqual(output.values.dtype, tf.int32)\n self.assertTrue(all(x < 10 and x >= 0 for x in output.values.eval()))\n self.assertAllEqual(output.indices.eval(), wire_tensor.indices.eval())\n self.assertAllEqual(output.shape.eval(), wire_tensor.shape.eval())\n\n def testWeightedSparseColumn(self):\n ids = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"marlo\", \"omar\", \"stringer\"])\n ids_tensor = tf.SparseTensor(values=[\"stringer\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, \"weights\")\n weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"ids\": ids_tensor,\n \"weights\": weights_tensor}\n output = feature_column_ops._Transformer(features).transform(weighted_ids)\n with self.test_session():\n tf.initialize_all_tables().run()\n self.assertAllEqual(output[0].shape.eval(), ids_tensor.shape.eval())\n self.assertAllEqual(output[0].indices.eval(), ids_tensor.indices.eval())\n self.assertAllEqual(output[0].values.eval(), [2, 2, 0])\n self.assertAllEqual(output[1].shape.eval(), weights_tensor.shape.eval())\n self.assertAllEqual(output[1].indices.eval(),\n weights_tensor.indices.eval())\n self.assertEqual(output[1].values.dtype, tf.float32)\n self.assertAllEqual(output[1].values.eval(), weights_tensor.values.eval())\n\n def testCrossColumn(self):\n language = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"language\", hash_bucket_size=3)\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_language = tf.contrib.layers.crossed_column(\n [language, country], hash_bucket_size=15)\n features = {\n \"language\": tf.SparseTensor(values=[\"english\", \"spanish\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1])\n }\n output = feature_column_ops._Transformer(features).transform(\n country_language)\n with self.test_session():\n self.assertEqual(output.values.dtype, tf.int64)\n self.assertTrue(all(x < 15 and x >= 0 for x in output.values.eval()))\n\n def testCrossWithBucketizedColumn(self):\n price_bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_price = tf.contrib.layers.crossed_column(\n [country, price_bucket], hash_bucket_size=15)\n features = {\n \"price\": tf.constant([[20.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2])\n }\n output = feature_column_ops._Transformer(features).transform(country_price)\n with self.test_session():\n self.assertEqual(output.values.dtype, tf.int64)\n self.assertTrue(all(x < 15 and x >= 0 for x in output.values.eval()))\n\n def testCrossWithMultiDimensionBucketizedColumn(self):\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n price_bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", 2),\n boundaries=[0., 10., 100.])\n country_price = tf.contrib.layers.crossed_column(\n [country, price_bucket], hash_bucket_size=1000)\n\n with tf.Graph().as_default():\n features = {\"price\": tf.constant([[20., 210.], [110., 50.], [-3., -30.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\", \"US\"],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 2])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [country_price],\n num_outputs=1))\n\n weights = column_to_variable[country_price][0]\n grad = tf.squeeze(tf.gradients(output, weights)[0].values)\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertEqual(len(grad.eval()), 6)\n\n def testCrossWithCrossedColumn(self):\n price_bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_price = tf.contrib.layers.crossed_column(\n [country, price_bucket], hash_bucket_size=15)\n wire = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_country_price = tf.contrib.layers.crossed_column(\n [wire, country_price], hash_bucket_size=15)\n features = {\n \"price\": tf.constant([[20.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2]),\n \"wire\": tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [0, 1], [0, 2]],\n shape=[1, 3])\n }\n output = feature_column_ops._Transformer(features).transform(\n wire_country_price)\n with self.test_session():\n self.assertEqual(output.values.dtype, tf.int64)\n self.assertTrue(all(x < 15 and x >= 0 for x in output.values.eval()))\n\n def testIfFeatureTableContainsTransformationReturnIt(self):\n any_column = tf.contrib.layers.sparse_column_with_hash_bucket(\"sparse\", 10)\n features = {any_column: \"any-thing-even-not-a-tensor\"}\n output = feature_column_ops._Transformer(features).transform(any_column)\n self.assertEqual(output, \"any-thing-even-not-a-tensor\")\n\n\nclass CreateInputLayersForDNNsTest(tf.test.TestCase):\n\n def testAllDNNColumns(self):\n sparse_column = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"a\", \"b\", \"c\", \"unseen\"])\n\n real_valued_column = tf.contrib.layers.real_valued_column(\"income\", 2)\n one_hot_column = tf.contrib.layers.one_hot_column(sparse_column)\n embedding_column = tf.contrib.layers.embedding_column(sparse_column, 10)\n features = {\n \"ids\": tf.SparseTensor(\n values=[\"c\", \"b\", \"a\"],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 1]),\n \"income\": tf.constant([[20.3, 10], [110.3, 0.4], [-3.0, 30.4]])\n }\n output = tf.contrib.layers.input_from_feature_columns(features,\n [one_hot_column,\n embedding_column,\n real_valued_column])\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n self.assertAllEqual(output.eval().shape, [3, 2 + 4 + 10])\n\n def testRealValuedColumn(self):\n real_valued = tf.contrib.layers.real_valued_column(\"price\")\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n output = tf.contrib.layers.input_from_feature_columns(features,\n [real_valued])\n with self.test_session():\n self.assertAllClose(output.eval(), features[\"price\"].eval())\n\n def testRealValuedColumnWithMultiDimensions(self):\n real_valued = tf.contrib.layers.real_valued_column(\"price\", 2)\n features = {\"price\": tf.constant([[20., 10.],\n [110, 0.],\n [-3, 30]])}\n output = tf.contrib.layers.input_from_feature_columns(features,\n [real_valued])\n with self.test_session():\n self.assertAllClose(output.eval(), features[\"price\"].eval())\n\n def testRealValuedColumnWithNormalizer(self):\n real_valued = tf.contrib.layers.real_valued_column(\n \"price\", normalizer=lambda x: x - 2)\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n output = tf.contrib.layers.input_from_feature_columns(features,\n [real_valued])\n with self.test_session():\n self.assertAllClose(output.eval(), features[\"price\"].eval() - 2)\n\n def testRealValuedColumnWithMultiDimensionsAndNormalizer(self):\n real_valued = tf.contrib.layers.real_valued_column(\n \"price\", 2, normalizer=lambda x: x - 2)\n features = {\"price\": tf.constant([[20., 10.], [110, 0.], [-3, 30]])}\n output = tf.contrib.layers.input_from_feature_columns(features,\n [real_valued])\n with self.test_session():\n self.assertAllClose(output.eval(), features[\"price\"].eval() - 2)\n\n def testBucketizedColumnSucceedsForDNN(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n output = tf.contrib.layers.input_from_feature_columns(features, [bucket])\n expected = [[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0]]\n with self.test_session():\n self.assertAllClose(output.eval(), expected)\n\n def testBucketizedColumnWithNormalizerSucceedsForDNN(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\n \"price\", normalizer=lambda x: x - 15),\n boundaries=[0., 10., 100.])\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n output = tf.contrib.layers.input_from_feature_columns(features, [bucket])\n expected = [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]\n with self.test_session():\n self.assertAllClose(output.eval(), expected)\n\n def testBucketizedColumnWithMultiDimensionsSucceedsForDNN(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", 2),\n boundaries=[0., 10., 100.])\n # buckets [2, 3], [3, 2], [0, 0]. dimension = 2\n features = {\"price\": tf.constant([[20., 200],\n [110, 50],\n [-3, -3]])}\n output = tf.contrib.layers.input_from_feature_columns(features, [bucket])\n expected = [[0, 0, 1, 0, 0, 0, 0, 1],\n [0, 0, 0, 1, 0, 0, 1, 0],\n [1, 0, 0, 0, 1, 0, 0, 0]]\n with self.test_session():\n self.assertAllClose(output.eval(), expected)\n\n def testOneHotColumnFromWeightedSparseColumnFails(self):\n ids_column = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"a\", \"b\", \"c\", \"unseen\"])\n ids_tensor = tf.SparseTensor(\n values=[\"c\", \"b\", \"a\", \"c\"],\n indices=[[0, 0], [1, 0], [2, 0], [2, 1]],\n shape=[3, 2])\n weighted_ids_column = tf.contrib.layers.weighted_sparse_column(ids_column,\n \"weights\")\n weights_tensor = tf.SparseTensor(\n values=[10.0, 20.0, 30.0, 40.0],\n indices=[[0, 0], [1, 0], [2, 0], [2, 1]],\n shape=[3, 2])\n features = {\"ids\": ids_tensor, \"weights\": weights_tensor}\n one_hot_column = tf.contrib.layers.one_hot_column(weighted_ids_column)\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n with self.assertRaisesRegexp(\n ValueError,\n \"one_hot_column does not yet support weighted_sparse_column\"):\n _ = tf.contrib.layers.input_from_feature_columns(features,\n [one_hot_column])\n\n def testOneHotColumnFromSparseColumnWithKeysSucceedsForDNN(self):\n ids_column = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"a\", \"b\", \"c\", \"unseen\"])\n ids_tensor = tf.SparseTensor(\n values=[\"c\", \"b\", \"a\"], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 1])\n one_hot_sparse = tf.contrib.layers.one_hot_column(ids_column)\n features = {\"ids\": ids_tensor}\n output = tf.contrib.layers.input_from_feature_columns(features,\n [one_hot_sparse])\n\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n self.assertAllEqual([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]],\n output.eval())\n\n def testOneHotColumnFromMultivalentSparseColumnWithKeysSucceedsForDNN(self):\n ids_column = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"a\", \"b\", \"c\", \"unseen\"])\n ids_tensor = tf.SparseTensor(\n values=[\"c\", \"b\", \"a\", \"c\"],\n indices=[[0, 0], [1, 0], [2, 0], [2, 1]],\n shape=[3, 2])\n one_hot_sparse = tf.contrib.layers.one_hot_column(ids_column)\n features = {\"ids\": ids_tensor}\n output = tf.contrib.layers.input_from_feature_columns(features,\n [one_hot_sparse])\n\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n self.assertAllEqual([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 1, 0]],\n output.eval())\n\n def testOneHotColumnFromSparseColumnWithIntegerizedFeaturePassesForDNN(self):\n ids_column = tf.contrib.layers.sparse_column_with_integerized_feature(\n \"ids\", bucket_size=4)\n one_hot_sparse = tf.contrib.layers.one_hot_column(ids_column)\n features = {\"ids\": tf.SparseTensor(\n values=[2, 1, 0, 2],\n indices=[[0, 0], [1, 0], [2, 0], [2, 1]],\n shape=[3, 2])}\n output = tf.contrib.layers.input_from_feature_columns(features,\n [one_hot_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 1, 0]],\n output.eval())\n\n def testOneHotColumnFromSparseColumnWithHashBucketSucceedsForDNN(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"feat\", 10)\n wire_tensor = tf.SparseTensor(\n values=[\"a\", \"b\", \"c1\", \"c2\"],\n indices=[[0, 0], [1, 0], [2, 0], [2, 1]],\n shape=[3, 2])\n features = {\"feat\": wire_tensor}\n one_hot_sparse = tf.contrib.layers.one_hot_column(hashed_sparse)\n output = tf.contrib.layers.input_from_feature_columns(features,\n [one_hot_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n self.assertAllEqual([3, 10], output.eval().shape)\n\n def testEmbeddingColumnSucceedsForDNN(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(\n values=[\"omar\", \"stringer\", \"marlo\", \"xx\", \"yy\"],\n indices=[[0, 0], [1, 0], [1, 1], [2, 0], [3, 0]],\n shape=[4, 2])\n features = {\"wire\": wire_tensor}\n embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10)\n output = tf.contrib.layers.input_from_feature_columns(features,\n [embeded_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(output.eval().shape, [4, 10])\n\n def testHashedEmbeddingColumnSucceedsForDNN(self):\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\", \"omar\"],\n indices=[[0, 0], [1, 0], [1, 1], [2, 0]],\n shape=[3, 2])\n\n features = {\"wire\": wire_tensor}\n # Big enough hash space so that hopefully there is no collision\n embedded_sparse = tf.contrib.layers.hashed_embedding_column(\"wire\", 1000, 3)\n output = tf.contrib.layers.input_from_feature_columns(\n features, [embedded_sparse], weight_collections=[\"my_collection\"])\n weights = tf.get_collection(\"my_collection\")\n grad = tf.gradients(output, weights)\n with self.test_session():\n tf.initialize_all_variables().run()\n gradient_values = []\n # Collect the gradient from the different partitions (one in this test)\n for p in range(len(grad)):\n gradient_values.extend(grad[p].values.eval())\n gradient_values.sort()\n self.assertAllEqual(gradient_values, [0.5]*6 + [2]*3)\n\n def testEmbeddingColumnWithInitializerSucceedsForDNN(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n init_value = 133.7\n embeded_sparse = tf.contrib.layers.embedding_column(\n hashed_sparse,\n 10, initializer=tf.constant_initializer(init_value))\n output = tf.contrib.layers.input_from_feature_columns(features,\n [embeded_sparse])\n\n with self.test_session():\n tf.initialize_all_variables().run()\n output_eval = output.eval()\n self.assertAllEqual(output_eval.shape, [2, 10])\n self.assertAllClose(output_eval, np.tile(init_value, [2, 10]))\n\n def testEmbeddingColumnWithMultipleInitializersFails(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n embedded_sparse = tf.contrib.layers.embedding_column(\n hashed_sparse,\n 10,\n initializer=tf.truncated_normal_initializer(mean=42,\n stddev=1337))\n embedded_sparse_alternate = tf.contrib.layers.embedding_column(\n hashed_sparse,\n 10,\n initializer=tf.truncated_normal_initializer(mean=1337,\n stddev=42))\n\n # Makes sure that trying to use different initializers with the same\n # embedding column explicitly fails.\n with self.test_session():\n with self.assertRaisesRegexp(\n ValueError,\n \"Duplicate feature column key found for column: wire_embedding\"):\n tf.contrib.layers.input_from_feature_columns(\n features, [embedded_sparse, embedded_sparse_alternate])\n\n def testEmbeddingColumnWithWeightedSparseColumnSucceedsForDNN(self):\n ids = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"marlo\", \"omar\", \"stringer\"])\n ids_tensor = tf.SparseTensor(values=[\"stringer\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, \"weights\")\n weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"ids\": ids_tensor,\n \"weights\": weights_tensor}\n embeded_sparse = tf.contrib.layers.embedding_column(weighted_ids, 10)\n output = tf.contrib.layers.input_from_feature_columns(features,\n [embeded_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n self.assertAllEqual(output.eval().shape, [2, 10])\n\n def testEmbeddingColumnWithCrossedColumnSucceedsForDNN(self):\n a = tf.contrib.layers.sparse_column_with_hash_bucket(\"aaa\",\n hash_bucket_size=100)\n b = tf.contrib.layers.sparse_column_with_hash_bucket(\"bbb\",\n hash_bucket_size=100)\n crossed = tf.contrib.layers.crossed_column(\n set([a, b]), hash_bucket_size=10000)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"aaa\": wire_tensor, \"bbb\": wire_tensor}\n embeded_sparse = tf.contrib.layers.embedding_column(crossed, 10)\n output = tf.contrib.layers.input_from_feature_columns(features,\n [embeded_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(output.eval().shape, [2, 10])\n\n def testSparseColumnFailsForDNN(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n with self.test_session():\n with self.assertRaisesRegexp(\n ValueError, \"Error creating input layer for column: wire\"):\n tf.initialize_all_variables().run()\n tf.contrib.layers.input_from_feature_columns(features, [hashed_sparse])\n\n def testWeightedSparseColumnFailsForDNN(self):\n ids = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"marlo\", \"omar\", \"stringer\"])\n ids_tensor = tf.SparseTensor(values=[\"stringer\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, \"weights\")\n weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"ids\": ids_tensor,\n \"weights\": weights_tensor}\n with self.test_session():\n with self.assertRaisesRegexp(\n ValueError,\n \"Error creating input layer for column: ids_weighted_by_weights\"):\n tf.initialize_all_tables().run()\n tf.contrib.layers.input_from_feature_columns(features, [weighted_ids])\n\n def testCrossedColumnFailsForDNN(self):\n a = tf.contrib.layers.sparse_column_with_hash_bucket(\"aaa\",\n hash_bucket_size=100)\n b = tf.contrib.layers.sparse_column_with_hash_bucket(\"bbb\",\n hash_bucket_size=100)\n crossed = tf.contrib.layers.crossed_column(\n set([a, b]), hash_bucket_size=10000)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"aaa\": wire_tensor, \"bbb\": wire_tensor}\n with self.test_session():\n with self.assertRaisesRegexp(\n ValueError, \"Error creating input layer for column: aaa_X_bbb\"):\n tf.initialize_all_variables().run()\n tf.contrib.layers.input_from_feature_columns(features, [crossed])\n\n def testDeepColumnsSucceedForDNN(self):\n real_valued = tf.contrib.layers.real_valued_column(\"income\", 3)\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", 2),\n boundaries=[0., 10., 100.])\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n features = {\n \"income\": tf.constant([[20., 10, -5], [110, 0, -7], [-3, 30, 50]]),\n \"price\": tf.constant([[20., 200], [110, 2], [-20, -30]]),\n \"wire\": tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 1])\n }\n embeded_sparse = tf.contrib.layers.embedding_column(\n hashed_sparse,\n 10, initializer=tf.constant_initializer(133.7))\n output = tf.contrib.layers.input_from_feature_columns(\n features, [real_valued, bucket, embeded_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n # size of output = 3 (real_valued) + 2 * 4 (bucket) + 10 (embedding) = 21\n self.assertAllEqual(output.eval().shape, [3, 21])\n\n def testEmbeddingColumnForDNN(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n embeded_sparse = tf.contrib.layers.embedding_column(\n hashed_sparse, 1, combiner=\"sum\", initializer=init_ops.ones_initializer)\n output = tf.contrib.layers.input_from_feature_columns(features,\n [embeded_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n # score: (number of values)\n self.assertAllEqual(output.eval(), [[1.], [2.]])\n\n def testEmbeddingColumnWithWeightedSparseColumnForDNN(self):\n ids = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"marlo\", \"omar\", \"stringer\"])\n ids_tensor = tf.SparseTensor(values=[\"stringer\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, \"weights\")\n weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"ids\": ids_tensor,\n \"weights\": weights_tensor}\n embeded_sparse = tf.contrib.layers.embedding_column(\n weighted_ids, 1, combiner=\"sum\", initializer=init_ops.ones_initializer)\n output = tf.contrib.layers.input_from_feature_columns(features,\n [embeded_sparse])\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n # score: (sum of weights)\n self.assertAllEqual(output.eval(), [[10.], [50.]])\n\n def testInputLayerWithCollectionsForDNN(self):\n real_valued = tf.contrib.layers.real_valued_column(\"price\")\n bucket = tf.contrib.layers.bucketized_column(real_valued,\n boundaries=[0., 10., 100.])\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n features = {\n \"price\": tf.constant([[20.], [110], [-3]]),\n \"wire\": tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 1])\n }\n embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10)\n tf.contrib.layers.input_from_feature_columns(\n features, [real_valued, bucket, embeded_sparse],\n weight_collections=[\"my_collection\"])\n weights = tf.get_collection(\"my_collection\")\n # one variable for embeded sparse\n self.assertEqual(1, len(weights))\n\n def testInputLayerWithTrainableArgForDNN(self):\n real_valued = tf.contrib.layers.real_valued_column(\"price\")\n bucket = tf.contrib.layers.bucketized_column(real_valued,\n boundaries=[0., 10., 100.])\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n features = {\n \"price\": tf.constant([[20.], [110], [-3]]),\n \"wire\": tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 1])\n }\n embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10)\n tf.contrib.layers.input_from_feature_columns(\n features, [real_valued, bucket, embeded_sparse],\n weight_collections=[\"my_collection\"],\n trainable=False)\n # There should not be any trainable variables\n self.assertEqual(0, len(tf.trainable_variables()))\n\n tf.contrib.layers.input_from_feature_columns(\n features, [real_valued, bucket, embeded_sparse],\n weight_collections=[\"my_collection\"],\n trainable=True)\n # There should one trainable variable for embeded sparse\n self.assertEqual(1, len(tf.trainable_variables()))\n\n\nclass WeightedSumTest(tf.test.TestCase):\n\n def testSparseColumn(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [hashed_sparse], num_outputs=5)\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(logits.eval().shape, [2, 5])\n\n def testSparseIntColumn(self):\n \"\"\"Tests a sparse column with int values.\"\"\"\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"wire\", 10, dtype=tf.int64)\n wire_tensor = tf.SparseTensor(values=[101, 201, 301],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [hashed_sparse], num_outputs=5)\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(logits.eval().shape, [2, 5])\n\n def testWeightedSparseColumn(self):\n ids = tf.contrib.layers.sparse_column_with_keys(\n \"ids\", [\"marlo\", \"omar\", \"stringer\"])\n ids_tensor = tf.SparseTensor(values=[\"stringer\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, \"weights\")\n weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"ids\": ids_tensor,\n \"weights\": weights_tensor}\n logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [weighted_ids], num_outputs=5)\n with self.test_session():\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n self.assertAllEqual(logits.eval().shape, [2, 5])\n\n def testCrossedColumn(self):\n a = tf.contrib.layers.sparse_column_with_hash_bucket(\"aaa\",\n hash_bucket_size=100)\n b = tf.contrib.layers.sparse_column_with_hash_bucket(\"bbb\",\n hash_bucket_size=100)\n crossed = tf.contrib.layers.crossed_column(\n set([a, b]), hash_bucket_size=10000)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"aaa\": wire_tensor, \"bbb\": wire_tensor}\n logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [crossed], num_outputs=5)\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(logits.eval().shape, [2, 5])\n\n def testEmbeddingColumn(self):\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n wire_tensor = tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [1, 1]],\n shape=[2, 2])\n features = {\"wire\": wire_tensor}\n embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10)\n with self.test_session():\n with self.assertRaisesRegexp(\n ValueError, \"Error creating weighted sum for column: wire_embedding\"):\n tf.initialize_all_variables().run()\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [embeded_sparse],\n num_outputs=5)\n\n def testRealValuedColumnWithMultiDimensions(self):\n real_valued = tf.contrib.layers.real_valued_column(\"price\", 2)\n features = {\"price\": tf.constant([[20., 10.], [110, 0.], [-3, 30]])}\n logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [real_valued], num_outputs=5)\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(logits.eval().shape, [3, 5])\n\n def testBucketizedColumnWithMultiDimensions(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", 2),\n boundaries=[0., 10., 100.])\n features = {\"price\": tf.constant([[20., 10.], [110, 0.], [-3, 30]])}\n logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [bucket], num_outputs=5)\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(logits.eval().shape, [3, 5])\n\n def testAllWideColumns(self):\n real_valued = tf.contrib.layers.real_valued_column(\"income\", 2)\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket(\"wire\", 10)\n crossed = tf.contrib.layers.crossed_column([bucket, hashed_sparse], 100)\n features = {\n \"income\": tf.constant([[20., 10], [110, 0], [-3, 30]]),\n \"price\": tf.constant([[20.], [110], [-3]]),\n \"wire\": tf.SparseTensor(values=[\"omar\", \"stringer\", \"marlo\"],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 1])\n }\n output, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [real_valued, bucket, hashed_sparse, crossed],\n num_outputs=5)\n with self.test_session():\n tf.initialize_all_variables().run()\n self.assertAllEqual(output.eval().shape, [3, 5])\n\n def testPredictions(self):\n language = tf.contrib.layers.sparse_column_with_keys(\n column_name=\"language\",\n keys=[\"english\", \"finnish\", \"hindi\"])\n age = tf.contrib.layers.real_valued_column(\"age\")\n with tf.Graph().as_default():\n features = {\n \"age\": tf.constant([[1], [2]]),\n \"language\": tf.SparseTensor(values=[\"hindi\", \"english\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1]),\n }\n output, column_to_variable, bias = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [age, language],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n self.assertAllClose(output.eval(), [[0.], [0.]])\n\n sess.run(bias.assign([0.1]))\n self.assertAllClose(output.eval(), [[0.1], [0.1]])\n\n # score: 0.1 + age*0.1\n sess.run(column_to_variable[age][0].assign([[0.2]]))\n self.assertAllClose(output.eval(), [[0.3], [0.5]])\n\n # score: 0.1 + age*0.1 + language_weight[language_index]\n sess.run(column_to_variable[language][0].assign([[0.1], [0.3], [0.2]]))\n self.assertAllClose(output.eval(), [[0.5], [0.6]])\n\n def testJointPredictions(self):\n country = tf.contrib.layers.sparse_column_with_keys(\n column_name=\"country\",\n keys=[\"us\", \"finland\"])\n language = tf.contrib.layers.sparse_column_with_keys(\n column_name=\"language\",\n keys=[\"english\", \"finnish\", \"hindi\"])\n with tf.Graph().as_default():\n features = {\n \"country\": tf.SparseTensor(values=[\"finland\", \"us\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1]),\n \"language\": tf.SparseTensor(values=[\"hindi\", \"english\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1]),\n }\n output, variables, bias = (\n tf.contrib.layers.joint_weighted_sum_from_feature_columns(\n features, [country, language], num_outputs=1))\n # Assert that only a single weight is created.\n self.assertEqual(len(variables), 1)\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n self.assertAllClose(output.eval(), [[0.], [0.]])\n\n sess.run(bias.assign([0.1]))\n self.assertAllClose(output.eval(), [[0.1], [0.1]])\n\n # shape is [5,1] because 1 class and 2 + 3 features.\n self.assertEquals(variables[0].get_shape().as_list(), [5, 1])\n\n # score: bias + country_weight + language_weight\n sess.run(variables[0].assign([[0.1], [0.2], [0.3], [0.4], [0.5]]))\n self.assertAllClose(output.eval(), [[0.8], [0.5]])\n\n def testJointPredictionsWeightedFails(self):\n language = tf.contrib.layers.weighted_sparse_column(\n tf.contrib.layers.sparse_column_with_keys(\n column_name=\"language\",\n keys=[\"english\", \"finnish\", \"hindi\"]),\n \"weight\")\n with tf.Graph().as_default():\n features = {\n \"weight\": tf.constant([[1], [2]]),\n \"language\": tf.SparseTensor(values=[\"hindi\", \"english\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1]),\n }\n with self.assertRaises(AssertionError):\n tf.contrib.layers.joint_weighted_sum_from_feature_columns(\n features, [language], num_outputs=1)\n\n def testJointPredictionsRealFails(self):\n age = tf.contrib.layers.real_valued_column(\"age\")\n with tf.Graph().as_default():\n features = {\n \"age\": tf.constant([[1], [2]]),\n }\n with self.assertRaises(NotImplementedError):\n tf.contrib.layers.joint_weighted_sum_from_feature_columns(\n features, [age], num_outputs=1)\n\n def testPredictionsWithWeightedSparseColumn(self):\n language = tf.contrib.layers.sparse_column_with_keys(\n column_name=\"language\",\n keys=[\"english\", \"finnish\", \"hindi\"])\n weighted_language = tf.contrib.layers.weighted_sparse_column(\n sparse_id_column=language,\n weight_column_name=\"age\")\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(values=[\"hindi\", \"english\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1]),\n \"age\": tf.SparseTensor(values=[10.0, 20.0],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1])\n }\n output, column_to_variable, bias = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [weighted_language], num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n self.assertAllClose(output.eval(), [[0.], [0.]])\n\n sess.run(bias.assign([0.1]))\n self.assertAllClose(output.eval(), [[0.1], [0.1]])\n\n # score: bias + age*language_weight[index]\n sess.run(column_to_variable[weighted_language][0].assign(\n [[0.1], [0.2], [0.3]]))\n self.assertAllClose(output.eval(), [[3.1], [2.1]])\n\n def testPredictionsWithMultivalentColumnButNoCross(self):\n language = tf.contrib.layers.sparse_column_with_keys(\n column_name=\"language\",\n keys=[\"english\", \"turkish\", \"hindi\"])\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(values=[\"hindi\", \"english\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2])\n }\n output, column_to_variable, bias = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [language],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n # score: 0.1 + language_weight['hindi'] + language_weight['english']\n sess.run(bias.assign([0.1]))\n sess.run(column_to_variable[language][0].assign([[0.1], [0.3], [0.2]]))\n self.assertAllClose(output.eval(), [[0.4]])\n\n def testSparseFeatureColumnWithHashedBucketSize(self):\n movies = tf.contrib.layers.sparse_column_with_hash_bucket(\n column_name=\"movies\", hash_bucket_size=15)\n with tf.Graph().as_default():\n features = {\n \"movies\": tf.SparseTensor(\n values=[\"matrix\", \"head-on\", \"winter sleep\"],\n indices=[[0, 0], [0, 1], [1, 0]],\n shape=[2, 2])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [movies],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[movies][0]\n self.assertEqual(weights.get_shape(), (15, 1))\n sess.run(weights.assign(weights + 0.4))\n # score for first example = 0.4 (matrix) + 0.4 (head-on) = 0.8\n # score for second example = 0.4 (winter sleep)\n self.assertAllClose(output.eval(), [[0.8], [0.4]])\n\n def testCrossUsageInPredictions(self):\n language = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"language\", hash_bucket_size=3)\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_language = tf.contrib.layers.crossed_column(\n [language, country], hash_bucket_size=10)\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(values=[\"english\", \"spanish\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 1])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [country_language],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[country_language][0]\n sess.run(weights.assign(weights + 0.4))\n self.assertAllClose(output.eval(), [[0.4], [0.4]])\n\n def testCrossColumnByItself(self):\n language = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"language\", hash_bucket_size=3)\n language_language = tf.contrib.layers.crossed_column(\n [language, language], hash_bucket_size=10)\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(values=[\"english\", \"spanish\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2]),\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [language_language],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[language_language][0]\n sess.run(weights.assign(weights + 0.4))\n # There are two features inside language. If we cross it by itself we'll\n # have four crossed features.\n self.assertAllClose(output.eval(), [[1.6]])\n\n def testMultivalentCrossUsageInPredictions(self):\n language = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"language\", hash_bucket_size=3)\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_language = tf.contrib.layers.crossed_column(\n [language, country], hash_bucket_size=10)\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(values=[\"english\", \"spanish\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [country_language],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[country_language][0]\n sess.run(weights.assign(weights + 0.4))\n # There are four crosses each with 0.4 weight.\n # score = 0.4 + 0.4 + 0.4 + 0.4\n self.assertAllClose(output.eval(), [[1.6]])\n\n def testMultivalentCrossUsageInPredictionsWithPartition(self):\n # bucket size has to be big enough to allwo sharding.\n language = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"language\", hash_bucket_size=64 << 19)\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=64 << 18)\n country_language = tf.contrib.layers.crossed_column(\n [language, country], hash_bucket_size=64 << 18)\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(values=[\"english\", \"spanish\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2])\n }\n with tf.variable_scope(\n \"weighted_sum_from_feature_columns\",\n features.values(),\n partitioner=tf.min_max_variable_partitioner(\n max_partitions=10, min_slice_size=((64 << 20) - 1))) as scope:\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [country, language, country_language],\n num_outputs=1,\n scope=scope))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n self.assertEqual(2, len(column_to_variable[country]))\n self.assertEqual(3, len(column_to_variable[language]))\n self.assertEqual(2, len(column_to_variable[country_language]))\n\n weights = column_to_variable[country_language]\n for partition_variable in weights:\n sess.run(partition_variable.assign(partition_variable + 0.4))\n # There are four crosses each with 0.4 weight.\n # score = 0.4 + 0.4 + 0.4 + 0.4\n self.assertAllClose(output.eval(), [[1.6]])\n\n def testRealValuedColumnHavingMultiDimensions(self):\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n age = tf.contrib.layers.real_valued_column(\"age\")\n # The following RealValuedColumn has 3 dimensions.\n incomes = tf.contrib.layers.real_valued_column(\"incomes\", 3)\n\n with tf.Graph().as_default():\n features = {\"age\": tf.constant([[1], [1]]),\n \"incomes\": tf.constant([[100., 200., 300.], [10., 20., 30.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 2])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [country, age, incomes],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n incomes_weights = column_to_variable[incomes][0]\n sess.run(incomes_weights.assign([[0.1], [0.2], [0.3]]))\n self.assertAllClose(output.eval(), [[140.], [14.]])\n\n def testMulticlassWithRealValuedColumnHavingMultiDimensions(self):\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n age = tf.contrib.layers.real_valued_column(\"age\")\n # The following RealValuedColumn has 3 dimensions.\n incomes = tf.contrib.layers.real_valued_column(\"incomes\", 3)\n with tf.Graph().as_default():\n features = {\"age\": tf.constant([[1], [1]]),\n \"incomes\": tf.constant([[100., 200., 300.], [10., 20., 30.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [1, 0]],\n shape=[2, 2])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [country, age, incomes],\n num_outputs=5))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n incomes_weights = column_to_variable[incomes][0]\n sess.run(incomes_weights.assign([[0.01, 0.1, 1., 10., 100.],\n [0.02, 0.2, 2., 20., 200.],\n [0.03, 0.3, 3., 30., 300.]]))\n self.assertAllClose(output.eval(), [[14., 140., 1400., 14000., 140000.],\n [1.4, 14., 140., 1400., 14000.]])\n\n def testBucketizedColumn(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n with tf.Graph().as_default():\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20.], [110], [-3]])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [bucket],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n sess.run(column_to_variable[bucket][0].assign([[0.1], [0.2], [0.3], [0.4\n ]]))\n self.assertAllClose(output.eval(), [[0.3], [0.4], [0.1]])\n\n def testBucketizedColumnHavingMultiDimensions(self):\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", 2),\n boundaries=[0., 10., 100.])\n with tf.Graph().as_default():\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20., 210], [110, 50], [-3, -30]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [1, 0]],\n shape=[3, 2])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [bucket, country],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n # dimension = 2, bucket_size = 4, num_classes = 1\n sess.run(column_to_variable[bucket][0].assign(\n [[0.1], [0.2], [0.3], [0.4], [1], [2], [3], [4]]))\n self.assertAllClose(output.eval(), [[0.3 + 4], [0.4 + 3], [0.1 + 1]])\n\n def testMulticlassWithBucketizedColumnHavingMultiDimensions(self):\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", 2),\n boundaries=[0., 10., 100.])\n with tf.Graph().as_default():\n # buckets 2, 3, 0\n features = {\"price\": tf.constant([[20., 210], [110, 50], [-3, -30]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [1, 0]],\n shape=[3, 2])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [bucket, country],\n num_outputs=5))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n # dimension = 2, bucket_size = 4, num_classes = 5\n sess.run(column_to_variable[bucket][0].assign(\n [[0.1, 1, 10, 100, 1000], [0.2, 2, 20, 200, 2000],\n [0.3, 3, 30, 300, 3000], [0.4, 4, 40, 400, 4000],\n [5, 50, 500, 5000, 50000], [6, 60, 600, 6000, 60000],\n [7, 70, 700, 7000, 70000], [8, 80, 800, 8000, 80000]]))\n self.assertAllClose(\n output.eval(),\n [[0.3 + 8, 3 + 80, 30 + 800, 300 + 8000, 3000 + 80000],\n [0.4 + 7, 4 + 70, 40 + 700, 400 + 7000, 4000 + 70000],\n [0.1 + 5, 1 + 50, 10 + 500, 100 + 5000, 1000 + 50000]])\n\n def testCrossWithBucketizedColumn(self):\n price_bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_price = tf.contrib.layers.crossed_column(\n [country, price_bucket], hash_bucket_size=10)\n with tf.Graph().as_default():\n features = {\n \"price\": tf.constant([[20.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [country_price],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[country_price][0]\n sess.run(weights.assign(weights + 0.4))\n # There are two crosses each with 0.4 weight.\n # score = 0.4 + 0.4\n self.assertAllClose(output.eval(), [[0.8]])\n\n def testCrossWithCrossedColumn(self):\n price_bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n language = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"language\", hash_bucket_size=3)\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_language = tf.contrib.layers.crossed_column(\n [language, country], hash_bucket_size=10)\n country_language_price = tf.contrib.layers.crossed_column(\n set([country_language, price_bucket]),\n hash_bucket_size=15)\n with tf.Graph().as_default():\n features = {\n \"price\": tf.constant([[20.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2]),\n \"language\": tf.SparseTensor(values=[\"english\", \"spanish\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [country_language_price],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[country_language_price][0]\n sess.run(weights.assign(weights + 0.4))\n # There are two crosses each with 0.4 weight.\n # score = 0.4 + 0.4 + 0.4 + 0.4\n self.assertAllClose(output.eval(), [[1.6]])\n\n def testIntegerizedColumn(self):\n product = tf.contrib.layers.sparse_column_with_integerized_feature(\n \"product\", bucket_size=5)\n with tf.Graph().as_default():\n features = {\"product\": tf.SparseTensor(values=[0, 4, 2],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 1])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [product],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n product_weights = column_to_variable[product][0]\n sess.run(product_weights.assign([[0.1], [0.2], [0.3], [0.4], [0.5]]))\n self.assertAllClose(output.eval(), [[0.1], [0.5], [0.3]])\n\n def testIntegerizedColumnWithInvalidId(self):\n product = tf.contrib.layers.sparse_column_with_integerized_feature(\n \"product\", bucket_size=5)\n with tf.Graph().as_default():\n features = {\"product\": tf.SparseTensor(values=[5, 4, 7],\n indices=[[0, 0], [1, 0], [2, 0]],\n shape=[3, 1])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [product],\n num_outputs=1))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n product_weights = column_to_variable[product][0]\n sess.run(product_weights.assign([[0.1], [0.2], [0.3], [0.4], [0.5]]))\n self.assertAllClose(output.eval(), [[0.1], [0.5], [0.3]])\n\n def testMulticlassWithOnlyBias(self):\n with tf.Graph().as_default():\n features = {\"age\": tf.constant([[10.], [20.], [30.], [40.]])}\n output, _, bias = tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [tf.contrib.layers.real_valued_column(\"age\")],\n num_outputs=3)\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n sess.run(bias.assign([0.1, 0.2, 0.3]))\n self.assertAllClose(output.eval(), [[0.1, 0.2, 0.3], [0.1, 0.2, 0.3],\n [0.1, 0.2, 0.3], [0.1, 0.2, 0.3]])\n\n def testMulticlassWithRealValuedColumn(self):\n with tf.Graph().as_default():\n column = tf.contrib.layers.real_valued_column(\"age\")\n features = {\"age\": tf.constant([[10.], [20.], [30.], [40.]])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [column],\n num_outputs=3))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n weights = column_to_variable[column][0]\n self.assertEqual(weights.get_shape(), (1, 3))\n sess.run(weights.assign([[0.01, 0.03, 0.05]]))\n self.assertAllClose(output.eval(), [[0.1, 0.3, 0.5], [0.2, 0.6, 1.0],\n [0.3, 0.9, 1.5], [0.4, 1.2, 2.0]])\n\n def testMulticlassWithSparseColumn(self):\n with tf.Graph().as_default():\n column = tf.contrib.layers.sparse_column_with_keys(\n column_name=\"language\",\n keys=[\"english\", \"arabic\", \"hindi\", \"russian\", \"swahili\"])\n features = {\n \"language\": tf.SparseTensor(\n values=[\"hindi\", \"english\", \"arabic\", \"russian\"],\n indices=[[0, 0], [1, 0], [2, 0], [3, 0]],\n shape=[4, 1])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [column],\n num_outputs=3))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n weights = column_to_variable[column][0]\n self.assertEqual(weights.get_shape(), (5, 3))\n sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8],\n [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8,\n 1.1]]))\n self.assertAllClose(output.eval(), [[0.3, 0.6, 0.9], [0.1, 0.4, 0.7],\n [0.2, 0.5, 0.8], [0.4, 0.7, 1.0]])\n\n def testMulticlassWithBucketizedColumn(self):\n column = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 100., 500., 1000.])\n with tf.Graph().as_default():\n # buckets 0, 2, 1, 2\n features = {\"price\": tf.constant([[-3], [110], [20.], [210]])}\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [column],\n num_outputs=3))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[column][0]\n self.assertEqual(weights.get_shape(), (5, 3))\n sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8],\n [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8,\n 1.1]]))\n self.assertAllClose(output.eval(), [[0.1, 0.4, 0.7], [0.3, 0.6, 0.9],\n [0.2, 0.5, 0.8], [0.3, 0.6, 0.9]])\n\n def testMulticlassWithCrossedColumn(self):\n language = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"language\", hash_bucket_size=3)\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=2)\n column = tf.contrib.layers.crossed_column(\n {language, country}, hash_bucket_size=5)\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(\n values=[\"english\", \"spanish\", \"russian\", \"swahili\"],\n indices=[[0, 0], [1, 0], [2, 0], [3, 0]],\n shape=[4, 1]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\", \"RU\", \"KE\"],\n indices=[[0, 0], [1, 0], [2, 0], [3, 0]],\n shape=[4, 1])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [column],\n num_outputs=3))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[column][0]\n self.assertEqual(weights.get_shape(), (5, 3))\n sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8],\n [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8,\n 1.1]]))\n self.assertAllClose(tf.shape(output).eval(), [4, 3])\n\n def testMulticlassWithMultivalentColumn(self):\n column = tf.contrib.layers.sparse_column_with_keys(\n column_name=\"language\",\n keys=[\"english\", \"turkish\", \"hindi\", \"russian\", \"swahili\"])\n with tf.Graph().as_default():\n features = {\n \"language\": tf.SparseTensor(\n values=[\"hindi\", \"english\", \"turkish\", \"turkish\", \"english\"],\n indices=[[0, 0], [0, 1], [1, 0], [2, 0], [3, 0]],\n shape=[4, 2])\n }\n output, column_to_variable, _ = (\n tf.contrib.layers.weighted_sum_from_feature_columns(features,\n [column],\n num_outputs=3))\n with self.test_session() as sess:\n tf.initialize_all_variables().run()\n tf.initialize_all_tables().run()\n\n weights = column_to_variable[column][0]\n self.assertEqual(weights.get_shape(), (5, 3))\n sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8],\n [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8,\n 1.1]]))\n self.assertAllClose(output.eval(), [[0.4, 1.0, 1.6], [0.2, 0.5, 0.8],\n [0.2, 0.5, 0.8], [0.1, 0.4, 0.7]])\n\n def testVariablesAddedToCollection(self):\n price_bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\"),\n boundaries=[0., 10., 100.])\n country = tf.contrib.layers.sparse_column_with_hash_bucket(\n \"country\", hash_bucket_size=5)\n country_price = tf.contrib.layers.crossed_column(\n [country, price_bucket], hash_bucket_size=10)\n with tf.Graph().as_default():\n features = {\n \"price\": tf.constant([[20.]]),\n \"country\": tf.SparseTensor(values=[\"US\", \"SV\"],\n indices=[[0, 0], [0, 1]],\n shape=[1, 2])\n }\n tf.contrib.layers.weighted_sum_from_feature_columns(\n features, [country_price, price_bucket],\n num_outputs=1,\n weight_collections=[\"my_collection\"])\n weights = tf.get_collection(\"my_collection\")\n # 3 = bias + price_bucket + country_price\n self.assertEqual(3, len(weights))\n\n\nclass ParseExampleTest(tf.test.TestCase):\n\n def testParseExample(self):\n bucket = tf.contrib.layers.bucketized_column(\n tf.contrib.layers.real_valued_column(\"price\", dimension=3),\n boundaries=[0., 10., 100.])\n wire_cast = tf.contrib.layers.sparse_column_with_keys(\n \"wire_cast\", [\"marlo\", \"omar\", \"stringer\"])\n # buckets 2, 3, 0\n data = tf.train.Example(features=tf.train.Features(feature={\n \"price\": tf.train.Feature(float_list=tf.train.FloatList(value=[20., 110,\n -3])),\n \"wire_cast\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[\n b\"stringer\", b\"marlo\"\n ])),\n }))\n output = tf.contrib.layers.parse_feature_columns_from_examples(\n serialized=[data.SerializeToString()],\n feature_columns=[bucket, wire_cast])\n self.assertIn(bucket, output)\n self.assertIn(wire_cast, output)\n with self.test_session():\n tf.initialize_all_tables().run()\n self.assertAllEqual(output[bucket].eval(), [[2, 3, 0]])\n self.assertAllEqual(output[wire_cast].indices.eval(), [[0, 0], [0, 1]])\n self.assertAllEqual(output[wire_cast].values.eval(), [2, 0])\n\n\nclass InferRealValuedColumnTest(tf.test.TestCase):\n\n def testTensorInt32(self):\n self.assertEqual(\n tf.contrib.layers.infer_real_valued_columns(\n tf.zeros(shape=[33, 4], dtype=tf.int32)),\n [tf.contrib.layers.real_valued_column(\"\", dimension=4, dtype=tf.int32)])\n\n def testTensorInt64(self):\n self.assertEqual(\n tf.contrib.layers.infer_real_valued_columns(\n tf.zeros(shape=[33, 4], dtype=tf.int64)),\n [tf.contrib.layers.real_valued_column(\"\", dimension=4, dtype=tf.int64)])\n\n def testTensorFloat32(self):\n self.assertEqual(\n tf.contrib.layers.infer_real_valued_columns(\n tf.zeros(shape=[33, 4], dtype=tf.float32)),\n [tf.contrib.layers.real_valued_column(\n \"\", dimension=4, dtype=tf.float32)])\n\n def testTensorFloat64(self):\n self.assertEqual(\n tf.contrib.layers.infer_real_valued_columns(\n tf.zeros(shape=[33, 4], dtype=tf.float64)),\n [tf.contrib.layers.real_valued_column(\n \"\", dimension=4, dtype=tf.float64)])\n\n def testDictionary(self):\n self.assertItemsEqual(\n tf.contrib.layers.infer_real_valued_columns({\n \"a\": tf.zeros(shape=[33, 4], dtype=tf.int32),\n \"b\": tf.zeros(shape=[3, 2], dtype=tf.float32)\n }),\n [tf.contrib.layers.real_valued_column(\n \"a\", dimension=4, dtype=tf.int32),\n tf.contrib.layers.real_valued_column(\n \"b\", dimension=2, dtype=tf.float32)])\n\n def testNotGoodDtype(self):\n with self.assertRaises(ValueError):\n tf.contrib.layers.infer_real_valued_columns(\n tf.constant([[\"a\"]], dtype=tf.string))\n\n def testSparseTensor(self):\n with self.assertRaises(ValueError):\n tf.contrib.layers.infer_real_valued_columns(\n tf.SparseTensor(indices=[[0, 0]], values=[\"a\"], shape=[1, 1]))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# 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# ==============================================================================\n\n\"\"\"Tests for tensorflow.python.client.session.Session.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport threading\nimport time\n\nimport numpy as np\nimport six\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.core.lib.core import error_codes_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.util import compat\n\n\n# NOTE(mrry): Dummy shape registration for op used in the tests.\nops.RegisterShape('ConstructionFails')(None)\n\n\nclass SessionTest(test_util.TensorFlowTestCase):\n\n def testUseExistingGraph(self):\n with ops.Graph().as_default() as g, ops.device('/cpu:0'):\n a = constant_op.constant(6.0, shape=[1, 1])\n b = constant_op.constant(7.0, shape=[1, 1])\n c = math_ops.matmul(a, b, name='matmul')\n with session.Session(graph=g):\n result = c.eval()\n self.assertAllEqual(result, [[42.0]])\n\n def testUseDefaultGraph(self):\n with ops.Graph().as_default(), ops.device('/cpu:0'):\n a = constant_op.constant(6.0, shape=[1, 1])\n b = constant_op.constant(7.0, shape=[1, 1])\n c = math_ops.matmul(a, b, name='matmul')\n with session.Session():\n result = c.eval()\n self.assertAllEqual(result, [[42.0]])\n\n def testCreate(self):\n with session.Session():\n inp = constant_op.constant(10.0, shape=[2, 3], name='W1')\n copy = array_ops.identity(inp)\n # Test with feed.\n # TODO(mrry): Investigate why order='F' didn't work.\n arr = np.asarray([[0, 1, 2], [3, 4, 5]], dtype=np.float32, order='C')\n copy_val = copy.eval({'W1:0': arr})\n self.assertAllEqual(arr, copy_val)\n # Test without feed.\n copy_val = copy.eval()\n self.assertAllEqual(np.asarray([[10.0, 10.0, 10.0], [10.0, 10.0, 10.0]],\n dtype=np.float32), copy_val)\n\n def testManyCPUs(self):\n # TODO(keveman): Implement ListDevices and test for the number of\n # devices returned by ListDevices.\n with session.Session(\n config=config_pb2.ConfigProto(device_count={'CPU': 2})):\n inp = constant_op.constant(10.0, name='W1')\n self.assertAllEqual(inp.eval(), 10.0)\n\n def testPerSessionThreads(self):\n # TODO(keveman): Implement ListDevices and test for the number of\n # devices returned by ListDevices.\n with session.Session(\n config=config_pb2.ConfigProto(use_per_session_threads=True)):\n inp = constant_op.constant(10.0, name='W1')\n self.assertAllEqual(inp.eval(), 10.0)\n\n def testSessionInterOpThreadPool(self):\n config = config_pb2.ConfigProto()\n pool = config.session_inter_op_thread_pool.add()\n with session.Session(config=config) as s:\n inp = constant_op.constant(10.0, name='W1')\n results = s.run([inp])\n self.assertAllEqual([10.0], results)\n\n pool = config.session_inter_op_thread_pool.add()\n pool.num_threads = 1\n with session.Session(config=config) as s:\n inp = constant_op.constant(20.0, name='W2')\n results = s.run([inp])\n self.assertAllEqual([20.0], results)\n\n def testErrorsReported(self):\n with session.Session() as s:\n constant_op.constant(10.0, name='W1')\n with self.assertRaises(ValueError):\n s.run('foo:0')\n\n def testErrorPayload(self):\n with session.Session():\n a = array_ops.placeholder(dtypes.float32)\n with self.assertRaisesOpError(lambda e: e.op == a.op):\n a.eval()\n\n def testErrorCodeWithNoNodeDef(self):\n with session.Session() as s:\n a = array_ops.placeholder(dtypes.float32, shape=[])\n b = array_ops.placeholder(dtypes.float32, shape=[])\n r1 = math_ops.add(a, b)\n\n def exc_predicate(e):\n return (e.op is None and e.node_def is None and\n e.error_code == error_codes_pb2.INVALID_ARGUMENT)\n with self.assertRaisesOpError(exc_predicate):\n # Run with a bogus handle.\n s.partial_run('foo', r1, feed_dict={a: 1, b: 2})\n\n def testOpConstructionErrorPayload(self):\n with session.Session():\n failing_op = ops.get_default_graph().create_op(\n 'ConstructionFails', [], [], name='f')\n\n def exc_predicate(e):\n return (e.op == failing_op\n and e.error_code == error_codes_pb2.INVALID_ARGUMENT)\n with self.assertRaisesOpError(exc_predicate):\n failing_op.run()\n\n def testErrorBasedOn(self):\n with session.Session() as sess:\n a = constant_op.constant(0.0, shape=[2, 3])\n # NOTE(mrry): The original_op is nonsense, but used here to test that the\n # errors are reported correctly.\n # pylint: disable=protected-access\n with sess.graph._original_op(a.op):\n b = array_ops.identity(a, name='id')\n with sess.graph._original_op(b.op):\n c = array_ops.placeholder(dtypes.float32)\n # pylint: enable=protected-access\n\n def exc_predicate(e):\n return (e.op == c.op\n and e.op._original_op == b.op\n and e.op._original_op._original_op == a.op)\n with self.assertRaisesOpError(exc_predicate):\n c.eval()\n\n def testFetchNone(self):\n with session.Session() as s:\n a = constant_op.constant(1.0)\n with self.assertRaises(TypeError):\n s.run(None)\n with self.assertRaises(TypeError):\n s.run([None])\n with self.assertRaises(TypeError):\n s.run({'b': None})\n with self.assertRaises(TypeError):\n s.run({'a': a, 'b': None})\n\n def testFetchSingleton(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n res = sess.run(a)\n self.assertEqual(42.0, res)\n res = sess.run(a.op) # An op, not a tensor.\n self.assertEqual(None, res)\n\n def testFetchSingletonByName(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n res = sess.run(a.name)\n self.assertEqual(42.0, res)\n res = sess.run(a.op) # An op, not a tensor.\n self.assertEqual(None, res)\n\n def testFetchList(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n v = variables.Variable([54.0])\n assign = v.assign([63.0])\n res = sess.run([a, b, c, a.name, assign.op])\n self.assertTrue(isinstance(res, list))\n self.assertEqual(42.0, res[0])\n self.assertEqual(None, res[1])\n self.assertEqual(44.0, res[2])\n self.assertEqual(42.0, res[3])\n self.assertEqual(None, res[4])\n self.assertEqual(63.0, sess.run(v))\n\n def testFetchTuple(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n res = sess.run((a, b, c, a.name))\n self.assertTrue(isinstance(res, tuple))\n self.assertEqual(42.0, res[0])\n self.assertEqual(None, res[1])\n self.assertEqual(44.0, res[2])\n self.assertEqual(42.0, res[3])\n\n def testFetchNamedTuple(self):\n # pylint: disable=invalid-name\n ABC = collections.namedtuple('ABC', ['a', 'b', 'c'])\n # pylint: enable=invalid-name\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n res = sess.run(ABC(a, b, c))\n self.assertTrue(isinstance(res, ABC))\n self.assertEqual(42.0, res.a)\n self.assertEqual(None, res.b)\n self.assertEqual(44.0, res.c)\n\n def testFetchDict(self):\n with session.Session() as sess:\n a = constant_op.constant(42.0)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(44.0)\n res = sess.run({'a': a, 'b': b, 'c': c})\n self.assertTrue(isinstance(res, dict))\n self.assertEqual(42.0, res['a'])\n self.assertEqual(None, res['b'])\n self.assertEqual(44.0, res['c'])\n\n def testFetchNestingOneLevel(self):\n with session.Session() as sess:\n # pylint: disable=invalid-name\n ABC = collections.namedtuple('ABC', ['a', 'b', 'c'])\n DEFG = collections.namedtuple('DEFG', ['d', 'e', 'f', 'g'])\n # pylint: enable=invalid-name\n a_val = 42.0\n b_val = None\n c_val = 44.0\n a = constant_op.constant(a_val)\n b = control_flow_ops.no_op() # An op, not a tensor.\n c = constant_op.constant(c_val)\n # List of lists, tuples, namedtuple, and dict\n res = sess.run([[a, b, c], (a, b, c), ABC(a=a, b=b, c=c),\n {'a': a.name, 'c': c, 'b': b}])\n self.assertTrue(isinstance(res, list))\n self.assertTrue(isinstance(res[0], list))\n self.assertEqual(a_val, res[0][0])\n self.assertEqual(b_val, res[0][1])\n self.assertEqual(c_val, res[0][2])\n self.assertTrue(isinstance(res[1], tuple))\n self.assertEqual(a_val, res[1][0])\n self.assertEqual(b_val, res[1][1])\n self.assertEqual(c_val, res[1][2])\n self.assertTrue(isinstance(res[2], ABC))\n self.assertEqual(a_val, res[2].a)\n self.assertEqual(b_val, res[2].b)\n self.assertEqual(c_val, res[2].c)\n self.assertTrue(isinstance(res[3], dict))\n self.assertEqual(a_val, res[3]['a'])\n self.assertEqual(b_val, res[3]['b'])\n self.assertEqual(c_val, res[3]['c'])\n # Tuple of lists, tuples, namedtuple, and dict\n res = sess.run(([a, b, c], (a.name, b, c), ABC(a=a, b=b, c=c),\n {'a': a, 'c': c, 'b': b}))\n self.assertTrue(isinstance(res, tuple))\n self.assertTrue(isinstance(res[0], list))\n self.assertEqual(a_val, res[0][0])\n self.assertEqual(b_val, res[0][1])\n self.assertEqual(c_val, res[0][2])\n self.assertTrue(isinstance(res[1], tuple))\n self.assertEqual(a_val, res[1][0])\n self.assertEqual(b_val, res[1][1])\n self.assertEqual(c_val, res[1][2])\n self.assertTrue(isinstance(res[2], ABC))\n self.assertEqual(a_val, res[2].a)\n self.assertEqual(b_val, res[2].b)\n self.assertEqual(c_val, res[2].c)\n self.assertTrue(isinstance(res[3], dict))\n self.assertEqual(a_val, res[3]['a'])\n self.assertEqual(b_val, res[3]['b'])\n self.assertEqual(c_val, res[3]['c'])\n # Namedtuple of lists, tuples, namedtuples, and dict\n res = sess.run(DEFG(d=[a, b, c],\n e=(a, b, c),\n f=ABC(a=a.name, b=b, c=c),\n g={'a': a, 'c': c, 'b': b}))\n self.assertTrue(isinstance(res, DEFG))\n self.assertTrue(isinstance(res.d, list))\n self.assertEqual(a_val, res.d[0])\n self.assertEqual(b_val, res.d[1])\n self.assertEqual(c_val, res.d[2])\n self.assertTrue(isinstance(res.e, tuple))\n self.assertEqual(a_val, res.e[0])\n self.assertEqual(b_val, res.e[1])\n self.assertEqual(c_val, res.e[2])\n self.assertTrue(isinstance(res.f, ABC))\n self.assertEqual(a_val, res.f.a)\n self.assertEqual(b_val, res.f.b)\n self.assertEqual(c_val, res.f.c)\n self.assertTrue(isinstance(res.g, dict))\n self.assertEqual(a_val, res.g['a'])\n self.assertEqual(b_val, res.g['b'])\n self.assertEqual(c_val, res.g['c'])\n # Dict of lists, tuples, namedtuples, and dict\n res = sess.run({'d': [a, b, c],\n 'e': (a, b, c),\n 'f': ABC(a=a, b=b, c=c),\n 'g': {'a': a.name, 'c': c, 'b': b}})\n self.assertTrue(isinstance(res, dict))\n self.assertTrue(isinstance(res['d'], list))\n self.assertEqual(a_val, res['d'][0])\n self.assertEqual(b_val, res['d'][1])\n self.assertEqual(c_val, res['d'][2])\n self.assertTrue(isinstance(res['e'], tuple))\n self.assertEqual(a_val, res['e'][0])\n self.assertEqual(b_val, res['e'][1])\n self.assertEqual(c_val, res['e'][2])\n self.assertTrue(isinstance(res['f'], ABC))\n self.assertEqual(a_val, res['f'].a)\n self.assertEqual(b_val, res['f'].b)\n self.assertEqual(c_val, res['f'].c)\n self.assertTrue(isinstance(res['g'], dict))\n self.assertEqual(a_val, res['g']['a'])\n self.assertEqual(b_val, res['g']['b'])\n self.assertEqual(c_val, res['g']['c'])\n\n def testFetchTensorObject(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n results_with_list = s.run([c])\n self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_list[0])\n results_with_single = s.run(c)\n self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_single)\n results_with_get = c.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_get)\n a_val, b_val = s.run([a, b]) # Test multiple fetches.\n self.assertAllEqual([[1.0, 1.0]], a_val)\n self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]], b_val)\n results_with_dict = s.run({'a': [a], 'b': b, 'z': [a, b]})\n self.assertAllEqual([[1.0, 1.0]], results_with_dict['a'][0])\n self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]],\n results_with_dict['b'])\n self.assertAllEqual(results_with_dict['a'][0], results_with_dict['z'][0])\n self.assertAllEqual(results_with_dict['b'], results_with_dict['z'][1])\n\n # Test nested structures\n results_with_nested_list = s.run([[[a, b], b], a, [a, b]])\n self.assertAllEqual([[1.0, 1.0]], results_with_nested_list[0][0][0])\n self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]],\n results_with_nested_list[0][0][1])\n self.assertAllEqual(results_with_nested_list[0][0][0],\n results_with_nested_list[1])\n self.assertAllEqual(results_with_nested_list[1],\n results_with_nested_list[2][0])\n self.assertAllEqual(results_with_nested_list[0][0][1],\n results_with_nested_list[0][1])\n self.assertAllEqual(results_with_nested_list[0][1],\n results_with_nested_list[2][1])\n\n def testFetchScalar(self):\n with session.Session() as s:\n for scalar in np.int32, np.int64, np.float16, np.float32, np.float64:\n x = scalar(7)\n y = scalar(8)\n tf_x = constant_op.constant(x, shape=[])\n tf_y = constant_op.constant(y)\n tf_xy = math_ops.add(tf_x, tf_y)\n # Single fetch\n xy = s.run(tf_xy)\n self.assertEqual(scalar, type(xy))\n self.assertEqual(x + y, xy)\n # List fetch\n xy, = s.run([tf_xy])\n self.assertEqual(scalar, type(xy))\n self.assertEqual(x + y, xy)\n # Dict fetch\n xy = s.run({'xy': tf_xy})['xy']\n self.assertEqual(scalar, type(xy))\n self.assertEqual(x + y, xy)\n # Nested list fetch\n xy = s.run([[[tf_xy]], tf_xy, [tf_xy]])\n self.assertAllEqual(xy, [[[x + y]], x + y, [x + y]])\n self.assertEqual(scalar, type(xy[0][0][0]))\n self.assertEqual(scalar, type(xy[1]))\n self.assertEqual(scalar, type(xy[2][0]))\n\n def testFetchOperationObject(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n v = variables.Variable(a, name='testFetchOperationObject_v')\n s.run(v.initializer)\n v_val = s.run(v)\n self.assertAllEqual([[1.0, 1.0]], v_val)\n\n def testFetchSparseTensor(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = ops.SparseTensor(\n constant_op.constant(indices),\n constant_op.constant(values),\n constant_op.constant(shape))\n # Single fetch, use as tuple\n sp_out = s.run(sp)\n indices_out, values_out, shape_out = sp_out\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Single fetch, use as SparseTensorValue\n sp_out = s.run(sp)\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.shape, shape)\n # Tuple fetch, use as tuple\n indices_out, values_out, shape_out = s.run(sp)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # List fetch, use as tuple\n (indices_out, values_out, shape_out), = s.run([sp])\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # List fetch, use as SparseTensorValue\n sp_out, = s.run([sp])\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.shape, shape)\n # Dict fetch (single value), use as tuple\n indices_out, values_out, shape_out = s.run({'sp': sp})['sp']\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Dict fetch (list value), use as tuple\n (indices_out, values_out, shape_out), = s.run({'sp': [sp]})['sp']\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Dict fetch, use as SparseTensorValue\n sp_out = s.run({'sp': sp})['sp']\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.shape, shape)\n # Nested list fetch use as tuple\n sp_out = s.run([[[sp]], sp])\n indices_out, values_out, shape_out = sp_out[0][0][0]\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n indices_out, values_out, shape_out = sp_out[1]\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Nested list fetch, use as SparseTensorValue\n sp_out = s.run([[[sp]], sp])\n self.assertAllEqual(sp_out[0][0][0].indices, indices)\n self.assertAllEqual(sp_out[0][0][0].values, values)\n self.assertAllEqual(sp_out[0][0][0].shape, shape)\n self.assertAllEqual(sp_out[1].indices, indices)\n self.assertAllEqual(sp_out[1].values, values)\n self.assertAllEqual(sp_out[1].shape, shape)\n\n def testFeedSparseTensor(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = ops.SparseTensor(\n array_ops.placeholder(dtype=np.int64, shape=(2, 3)),\n array_ops.placeholder(dtype=np.float32, shape=(2,)),\n array_ops.placeholder(dtype=np.int64, shape=(3,)),)\n sp_indices = array_ops.identity(sp.indices)\n sp_values = array_ops.identity(sp.values)\n sp_shape = array_ops.identity(sp.shape)\n sp2 = ops.SparseTensor(sp_indices, sp_values, sp_shape)\n # Feed with tuple\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {sp: (indices, values, shape)})\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with tuple, fetch sp directly\n sp_out = s.run(sp, {sp: (indices, values, shape)})\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.shape, shape)\n # Feed with SparseTensorValue\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape],\n {sp: ops.SparseTensorValue(indices, values, shape)})\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue, fetch SparseTensorValue\n sp2_out = s.run(sp2, {sp: ops.SparseTensorValue(indices, values, shape)})\n self.assertAllEqual(sp2_out.indices, indices)\n self.assertAllEqual(sp2_out.values, values)\n self.assertAllEqual(sp2_out.shape, shape)\n # Feed SparseTensorValue and fetch sp directly.\n sp_out = s.run(sp, {sp: ops.SparseTensorValue(indices, values, shape)})\n self.assertAllEqual(sp_out.indices, indices)\n self.assertAllEqual(sp_out.values, values)\n self.assertAllEqual(sp_out.shape, shape)\n\n def testFeedSparsePlaceholder(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = array_ops.sparse_placeholder(dtype=np.float32, name='placeholder1')\n sp_indices = array_ops.identity(sp.indices)\n sp_values = array_ops.identity(sp.values)\n sp_shape = array_ops.identity(sp.shape)\n sp2 = ops.SparseTensor(sp_indices, sp_values, sp_shape)\n # Feed with tuple\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {sp: (indices, values, shape)})\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape],\n {sp: ops.SparseTensorValue(indices, values, shape)})\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n # Feed with SparseTensorValue, fetch SparseTensorValue\n sp2_out = s.run(sp2, {sp: ops.SparseTensorValue(indices, values, shape)})\n self.assertAllEqual(sp2_out.indices, indices)\n self.assertAllEqual(sp2_out.values, values)\n self.assertAllEqual(sp2_out.shape, shape)\n\n def testFeedSparePlaceholderConstantShape(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n shape = np.array([7, 9, 2]).astype(np.int64)\n sp = array_ops.sparse_placeholder(dtype=np.float32,\n shape=shape,\n name='placeholder1')\n self.assertAllEqual(sp.shape.eval(session=s), shape)\n self.assertAllEqual(tensor_util.constant_value(sp.shape), shape)\n sp_indices = array_ops.identity(sp.indices)\n sp_values = array_ops.identity(sp.values)\n sp_shape = array_ops.identity(sp.shape)\n # Feed with tuple\n indices_out, values_out, shape_out = s.run(\n [sp_indices, sp_values, sp_shape], {sp: (indices, values)})\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(shape_out, shape)\n\n def testFetchIndexedSlices(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n dense_shape = np.array([7, 9, 2]).astype(np.int64)\n ind = ops.IndexedSlices(\n constant_op.constant(values), constant_op.constant(indices),\n constant_op.constant(dense_shape))\n # Single fetch, use as tuple\n ind_out = s.run(ind)\n values_out, indices_out, dense_shape_out = ind_out\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Single fetch, use as IndexedSlicesValue\n ind_out = s.run(ind)\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n # Tuple fetch, use as tuple\n values_out, indices_out, dense_shape_out = s.run(ind)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as tuple\n (values_out, indices_out, dense_shape_out), = s.run([ind])\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as IndexedSlicesValue\n ind_out, = s.run([ind])\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n\n def testFeedIndexedSlices(self):\n with session.Session() as s:\n values = np.array([1.0, 2.0]).astype(np.float32)\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n dense_shape = np.array([7, 9, 2]).astype(np.int64)\n ind = ops.IndexedSlices(\n array_ops.placeholder(dtype=np.float32,\n shape=(2,)),\n array_ops.placeholder(dtype=np.int64,\n shape=(2, 3)),\n array_ops.placeholder(dtype=np.int64,\n shape=(3,)),)\n ind_values = array_ops.identity(ind.values)\n ind_indices = array_ops.identity(ind.indices)\n ind_dense_shape = array_ops.identity(ind.dense_shape)\n ind2 = ops.IndexedSlices(ind_values, ind_indices, ind_dense_shape)\n # Feed with tuple\n values_out, indices_out, dense_shape_out = s.run(\n [ind_values, ind_indices, ind_dense_shape],\n {ind: (values, indices, dense_shape)})\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Feed with IndexedSlicesValue\n values_out, indices_out, dense_shape_out = s.run(\n [ind_values, ind_indices, ind_dense_shape],\n {ind: ops.IndexedSlicesValue(values, indices, dense_shape)})\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Feed with IndexedSlicesValue, fetch IndexedSlicesValue\n ind2_out = s.run(ind2, {ind: ops.IndexedSlicesValue(values, indices,\n dense_shape)})\n self.assertAllEqual(ind2_out.values, values)\n self.assertAllEqual(ind2_out.indices, indices)\n self.assertAllEqual(ind2_out.dense_shape, dense_shape)\n\n def testFetchIndexedSlicesWithoutDenseShape(self):\n with session.Session() as s:\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n values = np.array([1.0, 2.0]).astype(np.float32)\n dense_shape = None\n ind = ops.IndexedSlices(\n constant_op.constant(values), constant_op.constant(indices), None)\n # Single fetch, use as tuple\n ind_out = s.run(ind)\n values_out, indices_out, dense_shape_out = ind_out\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # Single fetch, use as IndexedSlicesValue\n ind_out = s.run(ind)\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n # Tuple fetch, use as tuple\n values_out, indices_out, dense_shape_out = s.run(ind)\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as tuple\n (values_out, indices_out, dense_shape_out), = s.run([ind])\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n self.assertAllEqual(dense_shape_out, dense_shape)\n # List fetch, use as IndexedSlicesValue\n ind_out, = s.run([ind])\n self.assertAllEqual(ind_out.values, values)\n self.assertAllEqual(ind_out.indices, indices)\n self.assertAllEqual(ind_out.dense_shape, dense_shape)\n\n def testFeedIndexedSlicesWithoutDenseShape(self):\n with session.Session() as s:\n values = np.array([1.0, 2.0]).astype(np.float32)\n indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)\n dense_shape = None\n ind = ops.IndexedSlices(\n array_ops.placeholder(dtype=np.float32,\n shape=(2,)),\n array_ops.placeholder(dtype=np.int64,\n shape=(2, 3)),\n None)\n ind_values = array_ops.identity(ind.values)\n ind_indices = array_ops.identity(ind.indices)\n ind2 = ops.IndexedSlices(ind_values, ind_indices)\n # Feed with tuple\n values_out, indices_out = s.run(\n [ind_values, ind_indices], {ind: (values, indices)})\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n # Feed with IndexedSlicesValue\n values_out, indices_out = s.run(\n [ind_values, ind_indices],\n {ind: ops.IndexedSlicesValue(values, indices, dense_shape)})\n self.assertAllEqual(values_out, values)\n self.assertAllEqual(indices_out, indices)\n # Feed with IndexedSlicesValue, fetch IndexedSlicesValue\n ind2_out = s.run(ind2, {ind: ops.IndexedSlicesValue(values, indices,\n dense_shape)})\n self.assertAllEqual(ind2_out.values, values)\n self.assertAllEqual(ind2_out.indices, indices)\n self.assertAllEqual(ind2_out.dense_shape, dense_shape)\n\n def testExtendWithStatelessOperations(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n c_val = s.run(c)\n self.assertAllEqual([[4.0, 4.0, 4.0]], c_val)\n d = constant_op.constant([1.0, 2.0, 3.0], shape=[3, 1])\n e = math_ops.matmul(c, d)\n # Extend will happen here.\n e_val = s.run(e)\n self.assertAllEqual([[24.0]], e_val)\n\n def testExtendWithStatefulOperations(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n v = variables.Variable(c, name='testExtendWithStatefulOperations_v')\n v.initializer.run()\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n d = constant_op.constant(3.0, shape=[2, 3])\n e = math_ops.matmul(a, d)\n assign_e_to_v = state_ops.assign(v, e)\n # Extend will happen here.\n e_val = e.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n s.run(assign_e_to_v)\n v_val = v.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)\n\n def testExtendWithGroupBy(self):\n with session.Session() as s:\n a = constant_op.constant(1.0, shape=[1, 2])\n p = variables.Variable(a, name='testExtendWithGroupBy_p')\n a_val = a.eval() # Force an Extend after this op.\n self.assertAllEqual([[1.0, 1.0]], a_val)\n\n b = constant_op.constant(2.0, shape=[1, 2])\n q = variables.Variable(b, name='testExtendWithGroupBy_q')\n # Extend will happen here.\n init = control_flow_ops.group(p.initializer, q.initializer)\n s.run(init)\n p_val, q_val = s.run([p, q])\n\n self.assertAllEqual([[1.0, 1.0]], p_val)\n self.assertAllEqual([[2.0, 2.0]], q_val)\n\n def testTensorGetMethod(self):\n with session.Session():\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n\n c_val = c.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], c_val)\n\n fed_c_val = c.eval(feed_dict={a.name: [[4.0, 4.0]]})\n self.assertAllEqual([[16.0, 16.0, 16.0]], fed_c_val)\n\n def testOperationRunMethod(self):\n with session.Session():\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[1, 2], name='b')\n v = variables.Variable(a, a.dtype)\n assign_a_to_v = state_ops.assign(v, a)\n\n assign_a_to_v.eval()\n\n v_val = v.eval()\n self.assertAllEqual([[1.0, 1.0]], v_val)\n\n assign_b_to_v = state_ops.assign(v, b)\n\n assign_b_to_v.eval()\n v_val = v.eval()\n self.assertAllEqual([[2.0, 2.0]], v_val)\n\n assign_b_to_v.eval(feed_dict={'b:0': [[3.0, 3.0]]})\n v_val = v.eval()\n self.assertAllEqual([[3.0, 3.0]], v_val)\n\n def testDefaultGraph(self):\n with session.Session() as s:\n self.assertEqual(ops.get_default_graph(), s.graph)\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n self.assertEqual(ops.get_default_graph(), a.graph)\n self.assertEqual(ops.get_default_graph(), b.graph)\n c = math_ops.matmul(a, b)\n v = variables.Variable(c, name='testDefaultGraph_v')\n v.initializer.run()\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n d = constant_op.constant(3.0, shape=[2, 3])\n e = math_ops.matmul(a, d)\n assign_e_to_v = state_ops.assign(v, e)\n e_val = e.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n s.run(assign_e_to_v)\n v_val = v.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)\n self.assertEqual(ops.get_default_graph(), s.graph)\n\n def _testDefaultGraphInThread(self, constructed_event, continue_event, i):\n with session.Session() as s:\n self.assertEqual(ops.get_default_graph(), s.graph)\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n v = variables.Variable(c, name='var_%d' % i)\n\n # Block here until all threads have constructed their graph.\n constructed_event.set()\n continue_event.wait()\n\n assign_c_to_v = state_ops.assign(v, c)\n v.initializer.run()\n assign_c_to_v.eval()\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n d = constant_op.constant(3.0, shape=[2, 3])\n e = math_ops.matmul(a, d)\n assign_e_to_v = state_ops.assign(v, e)\n e_val = e.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)\n v_val = v.eval()\n self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)\n s.run(assign_e_to_v)\n v_val = v.eval()\n self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)\n self.assertEqual(ops.get_default_graph(), s.graph)\n\n def testDefaultGraphWithThreads(self):\n # Fork ten threads that use their thread-local default graph.\n threads = []\n constructed_events = [threading.Event() for _ in range(10)]\n continue_event = threading.Event()\n for i, constructed_event in enumerate(constructed_events):\n t = self.checkedThread(target=self._testDefaultGraphInThread,\n args=(constructed_event, continue_event, i))\n threads.append(t)\n for t in threads:\n t.start()\n for constructed_event in constructed_events:\n constructed_event.wait()\n continue_event.set()\n for t in threads:\n t.join()\n\n def testParallelRun(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n ev = threading.Event()\n\n def run_step():\n ev.wait()\n val = c.eval(session=sess)\n self.assertEqual(val, 5.0)\n threads = [self.checkedThread(target=run_step) for _ in range(100)]\n for t in threads:\n t.start()\n ev.set()\n for t in threads:\n t.join()\n\n def testRunFeedDict(self):\n with session.Session() as s:\n x = array_ops.zeros([2])\n\n y = s.run(2 * x, feed_dict={x: np.ones(2).astype(np.float32)})\n self.assertAllEqual(y, 2 * np.ones(2))\n\n y = s.run(2 * x, feed_dict={x.name: np.ones(2).astype(np.float32)})\n self.assertAllEqual(y, 2 * np.ones(2))\n\n y = s.run(2 * x, feed_dict={x: [1, 1]})\n assert (y == 2 * np.ones(2)).all()\n\n # Test nested tuple keys\n z = (((array_ops.zeros([2]),),), array_ops.zeros([2]),\n (array_ops.zeros([2]),))\n result = [z[0][0][0] * 2, z[1] * 2, z[2][0] * 2]\n values = (((np.array([1, 1]),),), np.array([2, 2]), (np.array([3, 3]),))\n result_value = s.run(result, feed_dict={z: values})\n self.assertAllEqual(result_value[0], 2 * np.ones(2))\n self.assertAllEqual(result_value[1], 2 * np.array([2, 2]))\n self.assertAllEqual(result_value[2], 2 * np.array([3, 3]))\n\n def testGraphDef(self):\n with session.Session() as sess:\n self.assertProtoEquals(\n 'versions { producer: %d min_consumer: %d }' % (\n versions.GRAPH_DEF_VERSION,\n versions.GRAPH_DEF_VERSION_MIN_CONSUMER),\n sess.graph_def)\n c = constant_op.constant(5.0, name='c')\n self.assertEquals(len(sess.graph_def.node), 1)\n d = constant_op.constant(6.0, name='d')\n self.assertEquals(len(sess.graph_def.node), 2)\n self.assertAllEqual(c.eval(), 5.0)\n self.assertAllEqual(d.eval(), 6.0)\n e = constant_op.constant(7.0, name='e')\n self.assertEquals(len(sess.graph_def.node), 3)\n self.assertAllEqual(e.eval(), 7.0)\n\n def testUseAfterClose(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n self.assertAllEqual(sess.run(c), 5.0)\n with self.assertRaisesWithPredicateMatch(\n RuntimeError, lambda e: 'Attempted to use a closed Session.' in str(e)):\n sess.run(c)\n\n def testUseAfterCloseConcurrent(self):\n with session.Session() as sess:\n c = constant_op.constant(5.0)\n self.assertAllEqual(sess.run(c), 5.0)\n\n def update_thread():\n with self.assertRaisesWithPredicateMatch(\n RuntimeError,\n lambda e: 'Attempted to use a closed Session.' in str(e)):\n while True:\n sess.run(c)\n t = threading.Thread(target=update_thread)\n t.start()\n time.sleep(0.1)\n sess.close()\n t.join()\n\n def testUseEmptyGraph(self):\n with session.Session() as sess:\n with self.assertRaisesWithPredicateMatch(\n RuntimeError, lambda e: 'The Session graph is empty.' in str(e)):\n sess.run([])\n\n def testNotEntered(self):\n # pylint: disable=protected-access\n self.assertEqual(ops._default_session_stack.get_default(), None)\n # pylint: enable=protected-access\n with ops.device('/cpu:0'):\n sess = session.Session()\n c_1 = constant_op.constant(5.0)\n with sess.graph.as_default():\n c_2 = constant_op.constant(5.0)\n self.assertEqual(c_1.graph, c_2.graph)\n self.assertEqual(sess.run(c_2), 5.0)\n with self.assertRaisesWithPredicateMatch(\n ValueError, lambda e: 'No default session is registered.' in str(e)):\n c_2.eval()\n\n def testInteractive(self):\n with ops.device('/cpu:0'):\n sess = session.InteractiveSession()\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n self.assertAllEqual([[4.0, 4.0, 4.0]], c.eval())\n d = constant_op.constant([1.0, 2.0, 3.0], shape=[3, 1])\n e = math_ops.matmul(c, d)\n self.assertAllEqual([[24.0]], e.eval())\n sess.close()\n\n def testInteractivePlacePrunedGraph(self):\n sess = session.InteractiveSession()\n\n # Build a graph that has a bad op in it (no kernel).\n #\n # This test currently does not link in any GPU kernels,\n # which is why placing this is invalid. If at some point\n # GPU kernels are added to this test, some other different\n # op / device combo should be chosen.\n with ops.device('/gpu:0'):\n a = constant_op.constant(1.0, shape=[1, 2])\n\n b = constant_op.constant(1.0, shape=[1, 2])\n\n # Only run the valid op, this should work.\n b.eval()\n\n with self.assertRaises(errors.InvalidArgumentError):\n a.eval()\n sess.close()\n\n def testDefaultSessionPlacePrunedGraph(self):\n sess = session.Session()\n\n # Build a graph that has a bad op in it (no kernel).\n #\n # This test currently does not link in any GPU kernels,\n # which is why placing this is invalid. If at some point\n # GPU kernels are added to this test, some other different\n # op / device combo should be chosen.\n with ops.device('/gpu:0'):\n _ = constant_op.constant(1.0, shape=[1, 2])\n\n b = constant_op.constant(1.0, shape=[1, 2])\n\n with self.assertRaises(errors.InvalidArgumentError):\n # Even though we don't run the bad op, we place the entire\n # graph, which should fail with a non-interactive session.\n sess.run(b)\n\n sess.close()\n\n def testSharedGraph(self):\n with ops.Graph().as_default() as g, ops.device('/cpu:0'):\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[2, 3])\n c = math_ops.matmul(a, b)\n\n with session.Session(graph=g) as sess1:\n with session.Session(graph=g) as sess2:\n self.assertAllEqual(sess1.run(c), sess2.run(c))\n\n def testDuplicatedInputs(self):\n with session.Session() as sess:\n a = constant_op.constant(1.0, shape=[1, 2])\n b = constant_op.constant(2.0, shape=[1, 3])\n a_val, b_val, a2_val = sess.run([a, b, a])\n self.assertAllEqual(a_val, [[1.0, 1.0]])\n self.assertAllEqual(b_val, [[2.0, 2.0, 2.0]])\n self.assertAllEqual(a2_val, [[1.0, 1.0]])\n\n def testFeedAndFetch(self):\n with session.Session() as sess:\n for dtype in [dtypes.float16,\n dtypes.float32,\n dtypes.float64,\n dtypes.int32,\n dtypes.uint8,\n dtypes.int16,\n dtypes.int8,\n dtypes.int64,\n dtypes.bool,\n dtypes.complex64,\n dtypes.complex128]:\n for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:\n np_dtype = dtype.as_numpy_dtype\n\n feed_t = array_ops.placeholder(dtype=dtype, shape=shape)\n out_t = array_ops.identity(feed_t)\n\n np_array = np.random.randint(-10, 10, shape)\n\n if dtype == dtypes.bool:\n np_array = np_array > 0\n elif dtype == dtypes.complex64:\n np_array = np.sqrt(np_array.astype(np_dtype))\n elif dtype == dtypes.complex64:\n np_array = np.sqrt(np_array.astype(np_dtype))\n else:\n np_array = np_array.astype(np_dtype)\n\n self.assertAllEqual(np_array,\n sess.run(out_t, feed_dict={feed_t: np_array}))\n # Check that we can also get the feed back.\n self.assertAllEqual(np_array,\n sess.run(feed_t, feed_dict={feed_t: np_array}))\n # Also check that we can get both back.\n out_v, feed_v = sess.run([out_t, feed_t],\n feed_dict={feed_t: np_array})\n self.assertAllEqual(np_array, out_v)\n self.assertAllEqual(np_array, feed_v)\n\n def testFeedError(self):\n with session.Session() as sess:\n feed_t = array_ops.placeholder(dtype=dtypes.float32)\n out_t = array_ops.identity(feed_t)\n feed_val = constant_op.constant(5.0)\n with self.assertRaisesRegexp(TypeError, 'cannot be a tf.Tensor object'):\n sess.run(out_t, feed_dict={feed_t: feed_val})\n with self.assertRaisesRegexp(TypeError, 'cannot be a tf.Tensor object'):\n out_t.eval(feed_dict={feed_t: feed_val})\n with self.assertRaisesRegexp(TypeError, 'cannot be a tf.Tensor object'):\n out_t.op.run(feed_dict={feed_t: feed_val})\n\n def testFeedPrecisionLossError(self):\n with session.Session() as sess:\n largest_int64 = np.iinfo(np.int64).max\n\n feed_int_implicit_int32 = constant_op.constant(1)\n feed_int_explicit_int32 = constant_op.constant(1, dtype=dtypes.int32)\n\n out_t = constant_op.constant(1.0)\n\n with self.assertRaisesRegexp(TypeError,\n 'is not compatible with Tensor type'):\n sess.run(out_t, feed_dict={feed_int_implicit_int32: largest_int64})\n with self.assertRaisesRegexp(TypeError,\n 'is not compatible with Tensor type'):\n sess.run(out_t, feed_dict={feed_int_explicit_int32: largest_int64})\n\n def testStringFetch(self):\n with session.Session():\n for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:\n size = 1\n for s in shape:\n size *= s\n c_list = np.array([compat.as_bytes(str(i)) for i in xrange(size)],\n dtype=np.object).reshape(shape) if size > 0 else []\n c = constant_op.constant(c_list)\n self.assertAllEqual(c.eval(), c_list)\n\n def testStringFeed(self):\n with session.Session() as sess:\n for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:\n size = 1\n for s in shape:\n size *= s\n c_list = np.array([compat.as_bytes(str(i)) for i in xrange(size)],\n dtype=np.object).reshape(shape)\n feed_t = array_ops.placeholder(dtype=dtypes.string, shape=shape)\n c = array_ops.identity(feed_t)\n self.assertAllEqual(sess.run(c, feed_dict={feed_t: c_list}), c_list)\n self.assertAllEqual(sess.run(feed_t, feed_dict={feed_t: c_list}),\n c_list)\n c_v, feed_v = sess.run([c, feed_t], feed_dict={feed_t: c_list})\n self.assertAllEqual(c_v, c_list)\n self.assertAllEqual(feed_v, c_list)\n\n def testStringFeedWithNullCharacters(self):\n with session.Session():\n c_list = [b'\\n\\x01\\x00', b'\\n\\x00\\x01']\n feed_t = array_ops.placeholder(dtype=dtypes.string, shape=[2])\n c = array_ops.identity(feed_t)\n out = c.eval(feed_dict={feed_t: c_list})\n self.assertEqual(c_list[0], out[0])\n self.assertEqual(c_list[1], out[1])\n\n def testStringFeedWithUnicode(self):\n with session.Session():\n c_list = [u'\\n\\x01\\x00', u'\\n\\x00\\x01',\n u'\\u26a3 unicode', u'\\U0001f60e deal with it']\n feed_t = array_ops.placeholder(dtype=dtypes.string, shape=[len(c_list)])\n c = array_ops.identity(feed_t)\n\n out = c.eval(feed_dict={feed_t: c_list})\n for i in range(len(c_list)):\n self.assertEqual(c_list[i], out[i].decode('utf-8'))\n\n out = c.eval(feed_dict={feed_t: np.array(c_list, dtype=np.object)})\n for i in range(len(c_list)):\n self.assertEqual(c_list[i], out[i].decode('utf-8'))\n\n def testInvalidTargetFails(self):\n with self.assertRaisesRegexp(\n errors.NotFoundError,\n 'No session factory registered for the given session options'):\n session.Session('INVALID_TARGET')\n\n def testFetchByNameDifferentStringTypes(self):\n with session.Session() as sess:\n c = constant_op.constant(42.0, name='c')\n d = constant_op.constant(43.0, name=u'd')\n e = constant_op.constant(44.0, name=b'e')\n f = constant_op.constant(45.0, name=r'f')\n\n self.assertTrue(isinstance(c.name, six.text_type))\n self.assertTrue(isinstance(d.name, six.text_type))\n self.assertTrue(isinstance(e.name, six.text_type))\n self.assertTrue(isinstance(f.name, six.text_type))\n\n self.assertEqual(42.0, sess.run('c:0'))\n self.assertEqual(42.0, sess.run(u'c:0'))\n self.assertEqual(42.0, sess.run(b'c:0'))\n self.assertEqual(42.0, sess.run(r'c:0'))\n\n self.assertEqual(43.0, sess.run('d:0'))\n self.assertEqual(43.0, sess.run(u'd:0'))\n self.assertEqual(43.0, sess.run(b'd:0'))\n self.assertEqual(43.0, sess.run(r'd:0'))\n\n self.assertEqual(44.0, sess.run('e:0'))\n self.assertEqual(44.0, sess.run(u'e:0'))\n self.assertEqual(44.0, sess.run(b'e:0'))\n self.assertEqual(44.0, sess.run(r'e:0'))\n\n self.assertEqual(45.0, sess.run('f:0'))\n self.assertEqual(45.0, sess.run(u'f:0'))\n self.assertEqual(45.0, sess.run(b'f:0'))\n self.assertEqual(45.0, sess.run(r'f:0'))\n\n def testIncorrectGraph(self):\n with ops.Graph().as_default() as g_1:\n c_1 = constant_op.constant(1.0, name='c')\n\n with ops.Graph().as_default() as g_2:\n c_2 = constant_op.constant(2.0, name='c')\n\n self.assertEqual('c', c_1.op.name)\n self.assertEqual('c', c_2.op.name)\n\n with session.Session(graph=g_1) as sess_1:\n self.assertEqual(1.0, sess_1.run(c_1))\n with self.assertRaises(ValueError):\n sess_1.run(c_2)\n with self.assertRaises(ValueError):\n sess_1.run(c_2.op)\n\n with session.Session(graph=g_2) as sess_2:\n with self.assertRaises(ValueError):\n sess_2.run(c_1)\n with self.assertRaises(ValueError):\n sess_2.run(c_1.op)\n self.assertEqual(2.0, sess_2.run(c_2))\n\n def testPartialRun(self):\n with session.Session() as sess:\n a = array_ops.placeholder(dtypes.float32, shape=[])\n b = array_ops.placeholder(dtypes.float32, shape=[])\n c = array_ops.placeholder(dtypes.float32, shape=[])\n r1 = math_ops.add(a, b)\n r2 = math_ops.mul(r1, c)\n\n h = sess.partial_run_setup([r1, r2], [a, b, c])\n res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2})\n self.assertEqual(3, res)\n temp = res * 17\n res = sess.partial_run(h, r2, feed_dict={c: temp})\n self.assertEqual(153, res)\n\n # Call again on the same graph.\n h2 = sess.partial_run_setup([r1, r2], [a, b, c])\n res = sess.partial_run(h2, r1, feed_dict={a: 1, b: 2})\n self.assertEqual(3, res)\n temp = res * 18\n res = sess.partial_run(h2, r2, feed_dict={c: temp})\n self.assertEqual(162, res)\n\n def testPartialRunIncomplete(self):\n with session.Session() as sess:\n a = array_ops.placeholder(dtypes.float32, shape=[])\n b = array_ops.placeholder(dtypes.float32, shape=[])\n c = array_ops.placeholder(dtypes.float32, shape=[])\n r1 = math_ops.add(a, b)\n r2 = math_ops.mul(r1, c)\n\n h = sess.partial_run_setup([r1, r2], [a, b, c])\n res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2})\n self.assertEqual(3, res)\n\n def testConcurrentPartialRun(self):\n with session.Session() as sess:\n a = array_ops.placeholder(dtypes.float32, shape=[])\n b = array_ops.placeholder(dtypes.float32, shape=[])\n c = array_ops.placeholder(dtypes.float32, shape=[])\n r1 = math_ops.add(a, b)\n r2 = math_ops.mul(r1, c)\n\n h1 = sess.partial_run_setup([r1], [a, b, c])\n h2 = sess.partial_run_setup([r1, r2], [a, b, c])\n res = sess.partial_run(h1, r1, feed_dict={a: 1, b: 2})\n self.assertEqual(3, res)\n temp = res * 19\n res = sess.partial_run(h2, r1, feed_dict={a: temp, b: 9})\n self.assertEqual(66, res)\n res = sess.partial_run(h2, r2, feed_dict={c: 7})\n self.assertEqual(462, res)\n\n def testManyPartialRun(self):\n with session.Session() as sess:\n steps = 200\n inputs = []\n outputs = []\n a = constant_op.constant(2.0, dtypes.float32)\n for i in xrange(steps):\n inputs.append(array_ops.placeholder(dtypes.float32, shape=[]))\n a = math_ops.mul(a, inputs[i])\n outputs.append(a)\n\n h = sess.partial_run_setup(outputs, inputs)\n for i in xrange(steps):\n res = sess.partial_run(h, outputs[i], feed_dict={inputs[i]: 1.0})\n self.assertEqual(2.0, res)\n\n feed_dict = {}\n for i in xrange(steps):\n feed_dict[inputs[i]] = 1.0\n res = sess.run(outputs, feed_dict)\n self.assertEqual(steps, len(res))\n self.assertEqual(2.0, res[-1])\n\n def testRunAndPartialRun(self):\n with session.Session() as sess:\n a = constant_op.constant(2.0, dtypes.float32)\n b = a * 2\n c = b * 3\n r1 = sess.run([b, c])\n h = sess.partial_run_setup([b, c], [])\n r2 = sess.partial_run(h, [b, c])\n self.assertEqual(r1, r2)\n\n def testFeedDictKeyException(self):\n with session.Session() as sess:\n a = constant_op.constant(1.0, dtypes.float32, name='a')\n with self.assertRaisesRegexp(TypeError, 'Cannot interpret feed_dict'):\n sess.run(a, feed_dict={'a': [2.0]})\n\n def testPerStepTrace(self):\n run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()\n\n with ops.device('/cpu:0'):\n with session.Session() as sess:\n sess.run(constant_op.constant(1.0))\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(constant_op.constant(1.0), run_metadata=run_metadata)\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(constant_op.constant(1.0),\n options=run_options,\n run_metadata=run_metadata)\n\n self.assertTrue(run_metadata.HasField('step_stats'))\n self.assertEquals(len(run_metadata.step_stats.dev_stats), 1)\n\n def testRunOptionsRunMetadata(self):\n run_options = config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE)\n run_metadata = config_pb2.RunMetadata()\n\n with ops.device('/cpu:0'):\n with session.Session() as sess:\n # all combinations are valid\n sess.run(constant_op.constant(1.0), options=None, run_metadata=None)\n sess.run(constant_op.constant(1.0), options=None,\n run_metadata=run_metadata)\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(constant_op.constant(1.0), options=run_options,\n run_metadata=None)\n self.assertTrue(not run_metadata.HasField('step_stats'))\n\n sess.run(constant_op.constant(1.0), options=run_options,\n run_metadata=run_metadata)\n\n self.assertTrue(run_metadata.HasField('step_stats'))\n self.assertEquals(len(run_metadata.step_stats.dev_stats), 1)\n\n def testFeedShapeCompatibility(self):\n with session.Session() as sess:\n some_tensor = constant_op.constant([2.0, 2.0, 2.0, 2.0])\n new_shape = constant_op.constant([2, 2])\n reshaped_tensor = array_ops.reshape(some_tensor, new_shape)\n\n with self.assertRaisesRegexp(ValueError, 'Cannot feed value of shape'):\n sess.run(reshaped_tensor, feed_dict={some_tensor: [1.0, 2.0, 3.0]})\n\n with self.assertRaisesRegexp(ValueError, 'may not be fed'):\n sess.run(reshaped_tensor, feed_dict={new_shape: [3, 7]})\n\n def testInferShapesFalse(self):\n with ops.Graph().as_default(), ops.device('/cpu:0'):\n a = constant_op.constant([[1, 2]])\n sess = session.Session()\n self.assertFalse('_output_shapes' in sess.graph_def.node[0].attr)\n # Avoid lint error regarding 'unused' var a.\n self.assertTrue(a == a)\n\n def testInferShapesTrue(self):\n config = config_pb2.ConfigProto(\n graph_options=config_pb2.GraphOptions(infer_shapes=True))\n with ops.Graph().as_default(), ops.device('/cpu:0'):\n a = constant_op.constant([[1, 2]])\n sess = session.Session(config=config)\n self.assertTrue('_output_shapes' in sess.graph_def.node[0].attr)\n # Avoid lint error regarding 'unused' var a.\n self.assertTrue(a == a)\n\n def testBuildCostModel(self):\n run_options = config_pb2.RunOptions()\n config = config_pb2.ConfigProto(\n allow_soft_placement=True,\n graph_options=config_pb2.GraphOptions(build_cost_model=100))\n with session.Session(config=config) as sess:\n with ops.device('/gpu:0'):\n a = array_ops.placeholder(dtypes.float32, shape=[])\n b = math_ops.add(a, a)\n c = array_ops.identity(b)\n d = math_ops.mul(c, c)\n for step in xrange(120):\n run_metadata = config_pb2.RunMetadata()\n sess.run(d, feed_dict={a: 1.0},\n options=run_options, run_metadata=run_metadata)\n if step == 99:\n self.assertTrue(run_metadata.HasField('cost_graph'))\n else:\n self.assertFalse(run_metadata.HasField('cost_graph'))\n\n def testNonInteractiveSessionNesting(self):\n sess1 = session.Session()\n sess1_controller = sess1.as_default()\n sess1_controller.__enter__()\n\n sess2 = session.Session()\n sess2_controller = sess2.as_default()\n sess2_controller.__enter__()\n\n with self.assertRaisesRegexp(AssertionError, 'Nesting violated'):\n sess1_controller.__exit__(None, None, None)\n\n ops._default_session_stack.reset()\n\n def testInteractiveSessionNesting(self):\n sess1 = session.InteractiveSession()\n sess2 = session.InteractiveSession()\n del sess1\n del sess2\n\n def testAsDefault(self):\n c = constant_op.constant(37)\n sess = session.Session()\n with sess.as_default():\n self.assertEqual(37, c.eval())\n\n # Ensure that the session remains valid even when it is not captured.\n with session.Session().as_default():\n self.assertEqual(37, c.eval())\n\n def testReentry(self):\n sess = session.Session()\n with self.assertRaisesRegexp(RuntimeError, 'not re-entrant'):\n with sess:\n with sess:\n pass\n\n def testInvalidArgument(self):\n with self.assertRaisesRegexp(TypeError, 'target must be a string'):\n session.Session(37)\n with self.assertRaisesRegexp(TypeError, 'config must be a tf.ConfigProto'):\n session.Session(config=37)\n with self.assertRaisesRegexp(TypeError, 'graph must be a tf.Graph'):\n session.Session(graph=37)\n\n def testTimeoutWithShortOperations(self):\n num_epochs = 5\n q = data_flow_ops.FIFOQueue(\n capacity=50, dtypes=[dtypes.int32], shapes=[()])\n enqueue_op = q.enqueue_many(constant_op.constant([1, 2]))\n\n # Use a 10-second timeout, which should be longer than any\n # non-blocking enqueue_many op.\n config = config_pb2.ConfigProto(operation_timeout_in_ms=10000)\n with session.Session(config=config) as sess:\n for _ in range(num_epochs):\n sess.run(enqueue_op)\n self.assertEqual(sess.run(q.size()), num_epochs * 2)\n\n\nif __name__ == '__main__':\n googletest.main()\n", "# Copyright 2016 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom scipy import stats\nimport tensorflow as tf\n\ndistributions = tf.contrib.distributions\n\n\nclass QuantizedDistributionTest(tf.test.TestCase):\n\n def setUp(self):\n self._rng = np.random.RandomState(0)\n\n def _assert_all_finite(self, array):\n self.assertTrue(np.isfinite(array).all())\n\n def test_quantization_of_uniform_with_cutoffs_having_no_effect(self):\n with self.test_session():\n # The Quantized uniform with cutoffs == None divides the real line into:\n # R = ...(-1, 0](0, 1](1, 2](2, 3](3, 4]...\n # j = ... 0 1 2 3 4 ...\n # Since this uniform (below) is supported on [0, 3],\n # it places 1/3 of its mass in the intervals j = 1, 2, 3.\n # Adding a cutoff at y = 0 changes the picture to\n # R = ...(-inf, 0](0, 1](1, 2](2, 3](3, 4]...\n # j = ... 0 1 2 3 4 ...\n # So the QUniform still places 1/3 of its mass in the intervals\n # j = 1, 2, 3.\n # Adding a cutoff at y = 3 changes the picture to\n # R = ...(-1, 0](0, 1](1, 2](2, inf)\n # j = ... 0 1 2 3\n # and the QUniform still places 1/3 of its mass in the intervals\n # j = 1, 2, 3.\n for lcut, ucut in [\n (None, None), (0.0, None), (None, 3.0), (0.0, 3.0), (-10., 10.)\n ]:\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Uniform,\n lower_cutoff=lcut,\n upper_cutoff=ucut,\n a=0.0,\n b=3.0)\n\n # pmf\n # uniform had no mass below -1.\n self.assertAllClose(0., qdist.pmf(-1.).eval())\n # uniform had no mass below 0.\n self.assertAllClose(0., qdist.pmf(0.).eval())\n # uniform put 1/3 of its mass in each of (0, 1], (1, 2], (2, 3],\n # which are the intervals j = 1, 2, 3.\n self.assertAllClose(1 / 3, qdist.pmf(1.).eval())\n self.assertAllClose(1 / 3, qdist.pmf(2.).eval())\n self.assertAllClose(1 / 3, qdist.pmf(3.).eval())\n # uniform had no mass in (3, 4] or (4, 5], which are j = 4, 5.\n self.assertAllClose(0 / 3, qdist.pmf(4.).eval())\n self.assertAllClose(0 / 3, qdist.pmf(5.).eval())\n\n # cdf\n self.assertAllClose(0., qdist.cdf(-1.).eval())\n self.assertAllClose(0., qdist.cdf(0.).eval())\n self.assertAllClose(1 / 3, qdist.cdf(1.).eval())\n self.assertAllClose(2 / 3, qdist.cdf(2.).eval())\n # Note fractional values allowed for cdfs of discrete distributions.\n # And adding 0.5 makes no difference because the quantized dist has\n # mass only on the integers, never in between.\n self.assertAllClose(2 / 3, qdist.cdf(2.5).eval())\n self.assertAllClose(3 / 3, qdist.cdf(3.).eval())\n self.assertAllClose(3 / 3, qdist.cdf(4.).eval())\n self.assertAllClose(3 / 3, qdist.cdf(5.).eval())\n\n def test_quantization_of_uniform_with_cutoffs_in_the_middle(self):\n with self.test_session():\n # The uniform is supported on [-3, 3]\n # Consider partitions the real line in intervals\n # ...(-3, -2](-2, -1](-1, 0](0, 1](1, 2](2, 3] ...\n # Before cutoffs, the uniform puts a mass of 1/6 in each interval written\n # above. Because of cutoffs, the qdist considers intervals and indices\n # ...(-infty, -1](-1, 0](0, infty) ...\n # -1 0 1\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Uniform,\n lower_cutoff=-1.0,\n upper_cutoff=1.0,\n a=-3.0,\n b=3.0)\n\n # pmf\n # Uniform had no mass on (-4, -3] or (-3, -2]\n self.assertAllClose(0., qdist.cdf(-3.).eval())\n self.assertAllClose(0., qdist.cdf(-2.).eval())\n # Uniform had 1/6 of its mass in each of (-3, -2], and (-2, -1], which\n # were collapsed into (-infty, -1], which is now the \"-1\" interval.\n self.assertAllClose(1 / 3, qdist.cdf(-1.).eval())\n # The j=0 interval contained mass from (-3, 0], which is 1/2 of the\n # uniform's mass.\n self.assertAllClose(1 / 2, qdist.cdf(0.).eval())\n # Adding 0.5 makes no difference because the quantized dist has mass on\n # the integers, not in between them.\n self.assertAllClose(1 / 2, qdist.cdf(0.5).eval())\n # After applying the cutoff, all mass was either in the interval\n # (0, infty), or below. (0, infty) is the interval indexed by j=1,\n # so pmf(1) should equal 1.\n self.assertAllClose(1., qdist.cdf(1.0).eval())\n # Since no mass of qdist is above 1,\n # pmf(10) = P[Y <= 10] = P[Y <= 1] = pmf(1).\n self.assertAllClose(1., qdist.cdf(10.0).eval())\n\n def test_quantization_of_batch_of_uniforms(self):\n batch_shape = (5, 5)\n with self.test_session():\n # The uniforms are supported on [0, 10]. The qdist considers the\n # intervals\n # ... (0, 1](1, 2]...(9, 10]...\n # with the intervals displayed above each holding 1 / 10 of the mass.\n # The qdist will be defined with no cutoffs,\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Uniform,\n lower_cutoff=None,\n upper_cutoff=None,\n a=tf.zeros(\n batch_shape, dtype=tf.float32),\n b=10 * tf.ones(\n batch_shape, dtype=tf.float32))\n\n # x is random integers in {-3,...,12}.\n x = self._rng.randint(-3, 13, size=batch_shape).astype(np.float32)\n\n # pmf\n # qdist.pmf(j) = 1 / 10 for j in {1,...,10}, and 0 otherwise,\n expected_pmf = (1 / 10) * np.ones(batch_shape)\n expected_pmf[x < 1] = 0.\n expected_pmf[x > 10] = 0.\n self.assertAllClose(expected_pmf, qdist.pmf(x).eval())\n\n # cdf\n # qdist.cdf(j)\n # = 0 for j < 1\n # = j / 10, for j in {1,...,10},\n # = 1, for j > 10.\n expected_cdf = x.copy() / 10\n expected_cdf[x < 1] = 0.\n expected_cdf[x > 10] = 1.\n self.assertAllClose(expected_cdf, qdist.cdf(x).eval())\n\n def test_sampling_from_batch_of_normals(self):\n batch_shape = (2,)\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n lower_cutoff=0.,\n upper_cutoff=None,\n mu=tf.zeros(\n batch_shape, dtype=tf.float32),\n sigma=tf.ones(\n batch_shape, dtype=tf.float32))\n\n samps = qdist.sample_n(n=5000, seed=42)\n samps_v = samps.eval()\n\n # With lower_cutoff = 0, the interval j=0 is (-infty, 0], which holds 1/2\n # of the mass of the normals.\n # rtol chosen to be 2x as large as necessary to pass.\n self.assertAllClose([0.5, 0.5], (samps_v == 0).mean(axis=0), rtol=0.03)\n\n # The interval j=1 is (0, 1], which is from the mean to one standard\n # deviation out. This should contain 0.6827 / 2 of the mass.\n self.assertAllClose(\n [0.6827 / 2, 0.6827 / 2], (samps_v == 1).mean(axis=0), rtol=0.03)\n\n def test_samples_agree_with_cdf_for_samples_over_large_range(self):\n # Consider the cdf for distribution X, F(x).\n # If U ~ Uniform[0, 1], then Y := F^{-1}(U) is distributed like X since\n # P[Y <= y] = P[F^{-1}(U) <= y] = P[U <= F(y)] = F(y).\n # If F is a bijection, we also have Z = F(X) is Uniform.\n #\n # Make an exponential with large mean (= 100). This ensures we will get\n # quantized values over a large range. This large range allows us to\n # pretend that the cdf F is a bijection, and hence F(X) is uniform.\n # Note that F cannot be bijection since it is constant between the\n # integers. Hence, F(X) (see below) will not be uniform exactly.\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Exponential,\n lam=0.01)\n # X ~ QuantizedExponential\n x = qdist.sample_n(n=10000, seed=42)\n # Z = F(X), should be Uniform.\n z = qdist.cdf(x)\n # Compare the CDF of Z to that of a Uniform.\n # dist = maximum distance between P[Z <= a] and P[U <= a].\n # We ignore pvalue, since of course this distribution is not exactly, and\n # with so many sample points we would get a false fail.\n dist, _ = stats.kstest(z.eval(), \"uniform\")\n\n # Since the distribution take values (approximately) in [0, 100], the\n # cdf should have jumps (approximately) every 1/100 of the way up.\n # Assert that the jumps are not more than 2/100.\n self.assertLess(dist, 0.02)\n\n def test_samples_agree_with_pdf_for_samples_over_small_range(self):\n # Testing that samples and pdf agree for a small range is important because\n # it makes sure the bin edges are consistent.\n\n # Make an exponential with mean 5.\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Exponential,\n lam=0.2)\n # Standard error should be less than 1 / (2 * sqrt(n_samples))\n n_samples = 10000\n std_err_bound = 1 / (2 * np.sqrt(n_samples))\n samps = qdist.sample((n_samples,), seed=42).eval()\n # The smallest value the samples can take on is 1, which corresponds to\n # the interval (0, 1]. Recall we use ceiling in the sampling definition.\n self.assertLess(0.5, samps.min())\n for x in range(1, 10):\n self.assertAllClose(\n qdist.pmf(float(x)).eval(),\n (samps == x).mean(),\n atol=std_err_bound)\n\n def test_normal_cdf_and_survival_function(self):\n # At integer values, the result should be the same as the standard normal.\n batch_shape = (3, 3)\n mu = self._rng.randn(*batch_shape)\n sigma = self._rng.rand(*batch_shape) + 1.0\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n mu=mu,\n sigma=sigma)\n sp_normal = stats.norm(mu, sigma)\n\n x = self._rng.randint(-5, 5, size=batch_shape).astype(np.float64)\n\n self.assertAllClose(\n sp_normal.cdf(x),\n qdist.cdf(x).eval())\n\n self.assertAllClose(\n sp_normal.sf(x),\n qdist.survival_function(x).eval())\n\n def test_normal_log_cdf_and_log_survival_function(self):\n # At integer values, the result should be the same as the standard normal.\n batch_shape = (3, 3)\n mu = self._rng.randn(*batch_shape)\n sigma = self._rng.rand(*batch_shape) + 1.0\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n mu=mu,\n sigma=sigma)\n sp_normal = stats.norm(mu, sigma)\n\n x = self._rng.randint(-10, 10, size=batch_shape).astype(np.float64)\n\n self.assertAllClose(\n sp_normal.logcdf(x),\n qdist.log_cdf(x).eval())\n\n self.assertAllClose(\n sp_normal.logsf(x),\n qdist.log_survival_function(x).eval())\n\n def test_normal_prob_with_cutoffs(self):\n # At integer values, the result should be the same as the standard normal.\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n mu=0.,\n sigma=1.,\n lower_cutoff=-2.,\n upper_cutoff=2.)\n sm_normal = stats.norm(0., 1.)\n # These cutoffs create partitions of the real line, and indices:\n # (-inf, -2](-2, -1](-1, 0](0, 1](1, inf)\n # -2 -1 0 1 2\n # Test interval (-inf, -2], <--> index -2.\n self.assertAllClose(\n sm_normal.cdf(-2),\n qdist.prob(-2.).eval(),\n atol=0)\n # Test interval (-2, -1], <--> index -1.\n self.assertAllClose(\n sm_normal.cdf(-1) - sm_normal.cdf(-2),\n qdist.prob(-1.).eval(),\n atol=0)\n # Test interval (-1, 0], <--> index 0.\n self.assertAllClose(\n sm_normal.cdf(0) - sm_normal.cdf(-1),\n qdist.prob(0.).eval(),\n atol=0)\n # Test interval (1, inf), <--> index 2.\n self.assertAllClose(\n 1. - sm_normal.cdf(1),\n qdist.prob(2.).eval(),\n atol=0)\n\n def test_normal_log_prob_with_cutoffs(self):\n # At integer values, the result should be the same as the standard normal.\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n mu=0.,\n sigma=1.,\n lower_cutoff=-2.,\n upper_cutoff=2.)\n sm_normal = stats.norm(0., 1.)\n # These cutoffs create partitions of the real line, and indices:\n # (-inf, -2](-2, -1](-1, 0](0, 1](1, inf)\n # -2 -1 0 1 2\n # Test interval (-inf, -2], <--> index -2.\n self.assertAllClose(\n np.log(sm_normal.cdf(-2)),\n qdist.log_prob(-2.).eval(),\n atol=0)\n # Test interval (-2, -1], <--> index -1.\n self.assertAllClose(\n np.log(sm_normal.cdf(-1) - sm_normal.cdf(-2)),\n qdist.log_prob(-1.).eval(),\n atol=0)\n # Test interval (-1, 0], <--> index 0.\n self.assertAllClose(\n np.log(sm_normal.cdf(0) - sm_normal.cdf(-1)),\n qdist.log_prob(0.).eval(),\n atol=0)\n # Test interval (1, inf), <--> index 2.\n self.assertAllClose(\n np.log(1. - sm_normal.cdf(1)),\n qdist.log_prob(2.).eval(),\n atol=0)\n\n def test_log_prob_and_grad_gives_finite_results(self):\n with self.test_session():\n for dtype in [np.float32, np.float64]:\n mu = tf.Variable(0., name=\"mu\", dtype=dtype)\n sigma = tf.Variable(1., name=\"sigma\", dtype=dtype)\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n mu=mu,\n sigma=sigma)\n x = np.arange(-100, 100, 2).astype(dtype)\n\n tf.initialize_all_variables().run()\n\n proba = qdist.log_prob(x)\n grads = tf.gradients(proba, [mu, sigma])\n\n self._assert_all_finite(proba.eval())\n self._assert_all_finite(grads[0].eval())\n self._assert_all_finite(grads[1].eval())\n\n def test_prob_and_grad_gives_finite_results_for_common_events(self):\n with self.test_session():\n mu = tf.Variable(0.0, name=\"mu\")\n sigma = tf.Variable(1.0, name=\"sigma\")\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n mu=mu,\n sigma=sigma)\n x = tf.ceil(4 * self._rng.rand(100).astype(np.float32) - 2)\n\n tf.initialize_all_variables().run()\n\n proba = qdist.prob(x)\n self._assert_all_finite(proba.eval())\n\n grads = tf.gradients(proba, [mu, sigma])\n self._assert_all_finite(grads[0].eval())\n self._assert_all_finite(grads[1].eval())\n\n def test_lower_cutoff_must_be_below_upper_cutoff_or_we_raise(self):\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n lower_cutoff=1., # not strictly less than upper_cutoff.\n upper_cutoff=1.,\n mu=0.,\n sigma=1.,\n validate_args=True)\n\n self.assertTrue(qdist.validate_args) # Default is True.\n with self.assertRaisesOpError(\"must be strictly less\"):\n qdist.sample().eval()\n\n def test_cutoffs_must_be_integer_valued_if_validate_args_true(self):\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n lower_cutoff=1.5,\n upper_cutoff=10.,\n mu=0.,\n sigma=1.,\n validate_args=True)\n\n self.assertTrue(qdist.validate_args) # Default is True.\n with self.assertRaisesOpError(\"has non-integer components\"):\n qdist.sample().eval()\n\n def test_cutoffs_can_be_float_valued_if_validate_args_false(self):\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n lower_cutoff=1.5,\n upper_cutoff=10.11,\n mu=0.,\n sigma=1.,\n validate_args=False)\n\n self.assertFalse(qdist.validate_args) # Default is True.\n\n # Should not raise\n qdist.sample().eval()\n\n def test_dtype_and_shape_inherited_from_base_dist(self):\n batch_shape = (2, 3)\n with self.test_session():\n qdist = distributions.QuantizedDistribution(\n base_dist_cls=distributions.Normal,\n lower_cutoff=1.0,\n upper_cutoff=10.0,\n mu=tf.zeros(batch_shape),\n sigma=tf.ones(batch_shape))\n\n self.assertEqual(batch_shape, qdist.get_batch_shape())\n self.assertAllEqual(batch_shape, qdist.batch_shape().eval())\n self.assertEqual((), qdist.get_event_shape())\n self.assertAllEqual((), qdist.event_shape().eval())\n\n samps = qdist.sample_n(n=10)\n self.assertEqual((10,) + batch_shape, samps.get_shape())\n self.assertAllEqual((10,) + batch_shape, samps.eval().shape)\n\n y = self._rng.randint(0, 5, size=batch_shape).astype(np.float32)\n self.assertEqual(batch_shape, qdist.prob(y).get_shape())\n self.assertEqual(batch_shape, qdist.prob(y).eval().shape)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2016 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\"\"\"Tests for Cudnn RNN models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.python.framework.test_util import TensorFlowTestCase\nfrom tensorflow.python.platform import googletest\n\n\nclass CudnnRNNTest(TensorFlowTestCase):\n\n def _CreateModel(self, rnn_mode, num_layers, num_units, input_size):\n if rnn_mode == \"lstm\":\n model = tf.contrib.cudnn_rnn.CudnnLSTM(num_layers, num_units, input_size)\n elif rnn_mode == \"gru\":\n model = tf.contrib.cudnn_rnn.CudnnGRU(num_layers, num_units, input_size)\n elif rnn_mode == \"rnn_tanh\":\n model = tf.contrib.cudnn_rnn.CudnnRNNTanh(num_layers, num_units,\n input_size)\n elif rnn_mode == \"rnn_relu\":\n model = tf.contrib.cudnn_rnn.CudnnRNNRelu(num_layers, num_units,\n input_size)\n else:\n raise ValueError(\"Invalid rnn_mode: %s\" % rnn_mode)\n return model\n\n def _MinLSTMParamSize(self,\n num_layers,\n num_units,\n input_size,\n input_mode=\"auto_select\",\n direction=\"unidirection\"):\n if direction != \"unidirection\":\n # TODO(zhengxq): support bidirection in parameter size estimate.\n raise ValueError(\"Only unidirection in parameter size estimate\")\n first_layer_weights = 4 * num_units * (num_units + input_size)\n higher_layer_weights = 8 * (num_layers - 1) * num_units * num_units\n all_biases = 8 * num_layers * num_units\n return first_layer_weights + higher_layer_weights + all_biases\n\n def _testOneLSTMParamsSize(self, num_layers, num_units, input_size):\n min_params_size = self._MinLSTMParamSize(num_layers, num_units, input_size)\n model = self._CreateModel(\"lstm\", num_layers, num_units, input_size)\n params_size = model.params_size()\n with self.test_session(use_gpu=True) as sess:\n params_size_v = sess.run(params_size)\n self.assertLessEqual(min_params_size, params_size_v)\n\n def testLSTMParamsSize(self):\n if not tf.test.is_built_with_cuda():\n return\n test_configs = [\n [4, 200, 200],\n [4, 200, 300],\n [4, 200, 100],\n [1, 100, 200],\n [2, 200, 100],\n [3, 200, 400],\n ]\n with tf.Graph().as_default():\n for (num_layers, num_units, input_size) in test_configs:\n self._testOneLSTMParamsSize(num_layers, num_units, input_size)\n\n def _testOneSimpleInference(self, rnn_mode, num_layers, num_units, input_size,\n batch_size, seq_length, dir_count, expected,\n tolerance):\n model = self._CreateModel(rnn_mode, num_layers, num_units, input_size)\n has_input_c = (rnn_mode == \"lstm\")\n params_size_t = model.params_size()\n input_data = tf.ones([seq_length, batch_size, input_size])\n input_h = tf.ones([num_layers * dir_count, batch_size, num_units])\n if has_input_c:\n input_c = tf.ones([num_layers * dir_count, batch_size, num_units])\n params = tf.Variable(tf.ones([params_size_t]), validate_shape=False)\n if has_input_c:\n output, output_h, output_c = model(\n input_data=input_data,\n input_h=input_h,\n input_c=input_c,\n params=params,\n is_training=False)\n else:\n output, output_h = model(\n input_data=input_data,\n input_h=input_h,\n params=params,\n is_training=False)\n output_sum = tf.reduce_sum(output)\n output_h_sum = tf.reduce_sum(output_h)\n total_sum = output_sum + output_h_sum\n if has_input_c:\n output_c_sum = tf.reduce_sum(output_c)\n total_sum += output_c_sum\n with self.test_session(use_gpu=True) as sess:\n sess.run(tf.initialize_all_variables())\n total_sum_v = sess.run([total_sum])\n self.assertAllClose(\n total_sum_v[0], expected, atol=tolerance, rtol=tolerance)\n\n def testSimpleInference(self):\n if not tf.test.is_built_with_cuda():\n return\n test_configs = [\n [\"lstm\",\n 231833.22,\n 1e-2,\n {\n \"num_layers\": 4,\n \"num_units\": 200,\n \"input_size\": 200,\n \"batch_size\": 20,\n \"seq_length\": 10,\n \"dir_count\": 1,\n },],\n [\"gru\",\n 56000,\n 1e-2,\n {\n \"num_layers\": 4,\n \"num_units\": 200,\n \"input_size\": 200,\n \"batch_size\": 20,\n \"seq_length\": 10,\n \"dir_count\": 1,\n },],\n [\"rnn_tanh\",\n 56000,\n 1e-2,\n {\n \"num_layers\": 4,\n \"num_units\": 200,\n \"input_size\": 200,\n \"batch_size\": 20,\n \"seq_length\": 10,\n \"dir_count\": 1,\n },],\n [\"rnn_relu\",\n 130688,\n 1e-2,\n {\n \"num_layers\": 2,\n \"num_units\": 8,\n \"input_size\": 4,\n \"batch_size\": 4,\n \"seq_length\": 2,\n \"dir_count\": 1,\n },],\n ]\n with tf.Graph().as_default():\n for config in test_configs:\n rnn_mode = config[0]\n expected = config[1]\n tolerance = config[2]\n shapes = config[3]\n self._testOneSimpleInference(rnn_mode, shapes[\"num_layers\"],\n shapes[\"num_units\"], shapes[\"input_size\"],\n shapes[\"batch_size\"], shapes[\"seq_length\"],\n shapes[\"dir_count\"], expected, tolerance)\n\n def _testOneSimpleTraining(self, rnn_mode, num_layers, num_units, input_size,\n batch_size, seq_length, dir_count, tolerance):\n has_input_c = (rnn_mode == \"lstm\")\n tf.set_random_seed(1234)\n model = self._CreateModel(rnn_mode, num_layers, num_units, input_size)\n params_size_t = model.params_size()\n input_data = tf.Variable(\n tf.random_uniform([seq_length, batch_size, input_size]))\n input_h = tf.Variable(\n tf.random_uniform([num_layers * dir_count, batch_size, num_units]))\n if has_input_c:\n input_c = tf.Variable(\n tf.random_uniform([num_layers * dir_count, batch_size, num_units]))\n params = tf.Variable(\n tf.random_uniform([params_size_t]), validate_shape=False)\n if has_input_c:\n output, output_h, output_c = model(\n input_data=input_data,\n input_h=input_h,\n input_c=input_c,\n params=params)\n else:\n output, output_h = model(\n input_data=input_data, input_h=input_h, params=params)\n output_sum = tf.reduce_sum(output)\n output_h_sum = tf.reduce_sum(output_h)\n total_sum = output_sum + output_h_sum\n if has_input_c:\n output_c_sum = tf.reduce_sum(output_c)\n total_sum += output_c_sum\n\n with self.test_session(use_gpu=True) as sess:\n params_size_v = sess.run(params_size_t)\n inputs_and_shapes = [\n (input_data, [seq_length, batch_size, input_size]),\n (input_h, [num_layers * dir_count, batch_size, num_units]),\n (params, [params_size_v]),\n ]\n if has_input_c:\n inputs_and_shapes.append(\n (input_c, [num_layers * dir_count, batch_size, num_units]),)\n sess.run(tf.initialize_all_variables())\n all_inputs = [entry[0] for entry in inputs_and_shapes]\n all_shapes = [entry[1] for entry in inputs_and_shapes]\n err = tf.test.compute_gradient_error(all_inputs, all_shapes, total_sum,\n [1])\n self.assertLess(err, tolerance)\n\n def testSimpleTraining(self):\n if not tf.test.is_built_with_cuda():\n return\n test_configs = [\n [\"lstm\",\n 1e-2,\n {\n \"num_layers\": 2,\n \"num_units\": 3,\n \"input_size\": 4,\n \"batch_size\": 3,\n \"seq_length\": 4,\n \"dir_count\": 1,\n },],\n [\"gru\",\n 4e-3,\n {\n \"num_layers\": 2,\n \"num_units\": 3,\n \"input_size\": 4,\n \"batch_size\": 3,\n \"seq_length\": 4,\n \"dir_count\": 1,\n },],\n [\"rnn_tanh\",\n 5e-3,\n {\n \"num_layers\": 2,\n \"num_units\": 3,\n \"input_size\": 4,\n \"batch_size\": 3,\n \"seq_length\": 4,\n \"dir_count\": 1,\n },],\n [\"rnn_relu\",\n 3e-1,\n {\n \"num_layers\": 2,\n \"num_units\": 3,\n \"input_size\": 4,\n \"batch_size\": 3,\n \"seq_length\": 4,\n \"dir_count\": 1,\n },],\n ]\n with tf.Graph().as_default():\n for config in test_configs:\n rnn_mode = config[0]\n tolerance = config[1]\n shape = config[2]\n self._testOneSimpleTraining(rnn_mode, shape[\"num_layers\"],\n shape[\"num_units\"], shape[\"input_size\"],\n shape[\"batch_size\"], shape[\"seq_length\"],\n shape[\"dir_count\"], tolerance)\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# 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# ==============================================================================\n\n# pylint: disable=unused-import\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass PrettyPrintOpsTest(tf.test.TestCase):\n\n def testPrintTensorPassthrough(self):\n a = tf.constant([1])\n a = tf.contrib.framework.print_op(a)\n with self.test_session():\n self.assertEqual(a.eval(), tf.constant([1]).eval())\n\n def testPrintSparseTensorPassthrough(self):\n a = tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], shape=[3, 4])\n b = tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], shape=[3, 4])\n a = tf.contrib.framework.print_op(a)\n with self.test_session():\n self.assertAllEqual(tf.sparse_tensor_to_dense(a).eval(),\n tf.sparse_tensor_to_dense(b).eval())\n\n def testPrintTensorArrayPassthrough(self):\n a = tf.TensorArray(size=2, dtype=tf.int32, clear_after_read=False)\n a = a.write(1, 1)\n a = a.write(0, 0)\n a = tf.contrib.framework.print_op(a)\n with self.test_session():\n self.assertAllEqual(a.pack().eval(), tf.constant([0, 1]).eval())\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# 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# ==============================================================================\n\n\"\"\"Functional tests for Ftrl operations.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass FtrlOptimizerTest(tf.test.TestCase):\n\n def testFtrlwithoutRegularization(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session() as sess:\n var0 = tf.Variable([0.0, 0.0], dtype=dtype)\n var1 = tf.Variable([0.0, 0.0], dtype=dtype)\n grads0 = tf.constant([0.1, 0.2], dtype=dtype)\n grads1 = tf.constant([0.01, 0.02], dtype=dtype)\n opt = tf.train.FtrlOptimizer(3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n tf.initialize_all_variables().run()\n\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllClose([0.0, 0.0], v0_val)\n self.assertAllClose([0.0, 0.0], v1_val)\n\n # Run 3 steps FTRL\n for _ in range(3):\n update.run()\n\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllCloseAccordingToType(np.array([-2.60260963, -4.29698515]),\n v0_val)\n self.assertAllCloseAccordingToType(np.array([-0.28432083, -0.56694895]),\n v1_val)\n\n def testFtrlwithoutRegularization2(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session() as sess:\n var0 = tf.Variable([1.0, 2.0], dtype=dtype)\n var1 = tf.Variable([4.0, 3.0], dtype=dtype)\n grads0 = tf.constant([0.1, 0.2], dtype=dtype)\n grads1 = tf.constant([0.01, 0.02], dtype=dtype)\n\n opt = tf.train.FtrlOptimizer(3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n tf.initialize_all_variables().run()\n\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([4.0, 3.0], v1_val)\n\n # Run 3 steps FTRL\n for _ in range(3):\n update.run()\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllCloseAccordingToType(np.array([-2.55607247, -3.98729396]),\n v0_val)\n self.assertAllCloseAccordingToType(np.array([-0.28232238, -0.56096673]),\n v1_val)\n\n def testFtrlWithL1(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session() as sess:\n var0 = tf.Variable([1.0, 2.0], dtype=dtype)\n var1 = tf.Variable([4.0, 3.0], dtype=dtype)\n grads0 = tf.constant([0.1, 0.2], dtype=dtype)\n grads1 = tf.constant([0.01, 0.02], dtype=dtype)\n\n opt = tf.train.FtrlOptimizer(3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=0.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n tf.initialize_all_variables().run()\n\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([4.0, 3.0], v1_val)\n\n # Run 10 steps FTRL\n for _ in range(10):\n update.run()\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllCloseAccordingToType(\n np.array([-7.66718769, -10.91273689]),\n v0_val)\n self.assertAllCloseAccordingToType(\n np.array([-0.93460727, -1.86147261]),\n v1_val)\n\n def testFtrlWithL1_L2(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session() as sess:\n var0 = tf.Variable([1.0, 2.0], dtype=dtype)\n var1 = tf.Variable([4.0, 3.0], dtype=dtype)\n grads0 = tf.constant([0.1, 0.2], dtype=dtype)\n grads1 = tf.constant([0.01, 0.02], dtype=dtype)\n\n opt = tf.train.FtrlOptimizer(3.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.001,\n l2_regularization_strength=2.0)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n tf.initialize_all_variables().run()\n\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllCloseAccordingToType([1.0, 2.0], v0_val)\n self.assertAllCloseAccordingToType([4.0, 3.0], v1_val)\n\n # Run 10 steps FTRL\n for _ in range(10):\n update.run()\n\n v0_val, v1_val = sess.run([var0, var1])\n self.assertAllCloseAccordingToType(np.array([-0.24059935, -0.46829352]),\n v0_val)\n self.assertAllCloseAccordingToType(np.array([-0.02406147, -0.04830509]),\n v1_val)\n\n def applyOptimizer(self, opt, dtype, steps=5, is_sparse=False):\n if is_sparse:\n var0 = tf.Variable([[0.0], [0.0]], dtype=dtype)\n var1 = tf.Variable([[0.0], [0.0]], dtype=dtype)\n grads0 = tf.IndexedSlices(tf.constant([0.1], shape=[1, 1], dtype=dtype),\n tf.constant([0]),\n tf.constant([2, 1]))\n grads1 = tf.IndexedSlices(tf.constant([0.02], shape=[1, 1], dtype=dtype),\n tf.constant([1]),\n tf.constant([2, 1]))\n else:\n var0 = tf.Variable([0.0, 0.0], dtype=dtype)\n var1 = tf.Variable([0.0, 0.0], dtype=dtype)\n grads0 = tf.constant([0.1, 0.2], dtype=dtype)\n grads1 = tf.constant([0.01, 0.02], dtype=dtype)\n\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n tf.initialize_all_variables().run()\n\n sess = tf.get_default_session()\n v0_val, v1_val = sess.run([var0, var1])\n if is_sparse:\n self.assertAllCloseAccordingToType([[0.0], [0.0]], v0_val)\n self.assertAllCloseAccordingToType([[0.0], [0.0]], v1_val)\n else:\n self.assertAllCloseAccordingToType([0.0, 0.0], v0_val)\n self.assertAllCloseAccordingToType([0.0, 0.0], v1_val)\n\n # Run Ftrl for a few steps\n for _ in range(steps):\n update.run()\n\n v0_val, v1_val = sess.run([var0, var1])\n return v0_val, v1_val\n\n # When variables are initialized with Zero, FTRL-Proximal has two properties:\n # 1. Without L1&L2 but with fixed learning rate, FTRL-Proximal is identical\n # with GradientDescent.\n # 2. Without L1&L2 but with adaptive learning rate, FTRL-Proximal is identical\n # with Adagrad.\n # So, basing on these two properties, we test if our implementation of\n # FTRL-Proximal performs same updates as Adagrad or GradientDescent.\n def testEquivAdagradwithoutRegularization(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session():\n val0, val1 = self.applyOptimizer(\n tf.train.FtrlOptimizer(3.0,\n # Adagrad learning rate\n learning_rate_power=-0.5,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype)\n\n with self.test_session():\n val2, val3 = self.applyOptimizer(\n tf.train.AdagradOptimizer(3.0, initial_accumulator_value=0.1),\n dtype)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n def testEquivSparseAdagradwithoutRegularization(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session():\n val0, val1 = self.applyOptimizer(\n tf.train.FtrlOptimizer(3.0,\n # Adagrad learning rate\n learning_rate_power=-0.5,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype,\n is_sparse=True)\n\n with self.test_session():\n val2, val3 = self.applyOptimizer(\n tf.train.AdagradOptimizer(3.0, initial_accumulator_value=0.1),\n dtype, is_sparse=True)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n def testEquivSparseGradientDescentwithoutRegularization(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session():\n val0, val1 = self.applyOptimizer(\n tf.train.FtrlOptimizer(3.0,\n # Fixed learning rate\n learning_rate_power=-0.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype,\n is_sparse=True)\n\n with self.test_session():\n val2, val3 = self.applyOptimizer(\n tf.train.GradientDescentOptimizer(3.0), dtype, is_sparse=True)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n def testEquivGradientDescentwithoutRegularization(self):\n for dtype in [tf.half, tf.float32]:\n with self.test_session():\n val0, val1 = self.applyOptimizer(\n tf.train.FtrlOptimizer(3.0,\n # Fixed learning rate\n learning_rate_power=-0.0,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0),\n dtype)\n\n with self.test_session():\n val2, val3 = self.applyOptimizer(\n tf.train.GradientDescentOptimizer(3.0), dtype)\n\n self.assertAllCloseAccordingToType(val0, val2)\n self.assertAllCloseAccordingToType(val1, val3)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# 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# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy\nimport tensorflow as tf\n\n\nclass TraceTest(tf.test.TestCase):\n\n def setUp(self):\n x = numpy.random.seed(0)\n\n def traceOp(self, x, dtype, expected_ans, use_gpu=False):\n with self.test_session(use_gpu=use_gpu):\n tf_ans = tf.trace(x.astype(dtype))\n out = tf_ans.eval()\n self.assertAllClose(out, expected_ans)\n\n def testEmptyTensor(self):\n x = numpy.array([])\n self.assertRaises(ValueError, self.traceOp, x, numpy.float32, 0)\n\n def testRankOneTensor(self):\n x = numpy.array([1,2,3])\n self.assertRaises(ValueError, self.traceOp, x, numpy.float32, 0)\n\n def testRankTwoIntTensor(self):\n x = numpy.array(\n [[1, 0, 0],\n [0, 2, 0],\n [0, 0, 3]])\n expected_ans = 6\n self.traceOp(x, numpy.int32, expected_ans)\n self.traceOp(x, numpy.int64, expected_ans)\n\n def testRankTwoFloatTensor(self):\n x = numpy.array(\n [[1.1, 0, 0],\n [0, 2.2, 0],\n [0, 0, 3.3]])\n expected_ans = 6.6\n self.traceOp(x, numpy.float32, expected_ans)\n self.traceOp(x, numpy.float64, expected_ans)\n\n def testRankThreeFloatTensor(self):\n x = numpy.random.rand(2, 2, 2)\n self.assertRaises(ValueError, self.traceOp, x, numpy.float32, 0)\n\n def testRankFourFloatTensor(self):\n x = numpy.random.rand(2, 2, 2, 2)\n self.assertRaises(ValueError, self.traceOp, x, numpy.float32, 0)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# 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# ==============================================================================\n\"\"\"Utility functions for summary creation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport re\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import standard_ops\n\n__all__ = ['assert_summary_tag_unique', 'is_summary_tag_unique',\n 'summarize_tensor', 'summarize_activation', 'summarize_tensors',\n 'summarize_collection', 'summarize_variables', 'summarize_weights',\n 'summarize_biases', 'summarize_activations',]\n\n# TODO(wicke): add more unit tests for summarization functions.\n\n\ndef assert_summary_tag_unique(tag):\n if not is_summary_tag_unique(tag):\n raise ValueError('Conflict with summary tag: %s already exists' % tag)\n\n\ndef _add_scalar_summary(tensor, tag=None):\n \"\"\"Add a scalar summary operation for the tensor.\n\n Args:\n tensor: The tensor to summarize.\n tag: The tag to use, if None then use tensor's op's name.\n\n Returns:\n The created histogram summary.\n\n Raises:\n ValueError: If the tag is already in use or the rank is not 0.\n \"\"\"\n tensor.get_shape().assert_has_rank(0)\n tag = tag or tensor.op.name\n assert_summary_tag_unique(tag)\n return standard_ops.scalar_summary(tag, tensor, name='%s_summary' % tag)\n\n\ndef _add_histogram_summary(tensor, tag=None):\n \"\"\"Add a summary operation for the histogram of a tensor.\n\n Args:\n tensor: The tensor to summarize.\n tag: The tag to use, if None then use tensor's op's name.\n\n Returns:\n The created histogram summary.\n\n Raises:\n ValueError: If the tag is already in use.\n \"\"\"\n tag = tag or tensor.op.name\n assert_summary_tag_unique(tag)\n return standard_ops.histogram_summary(tag, tensor, name='%s_summary' % tag)\n\n\ndef is_summary_tag_unique(tag):\n \"\"\"Checks if a summary tag is unique.\n\n Args:\n tag: The tag to use\n\n Returns:\n True if the summary tag is unique.\n \"\"\"\n existing_tags = [tensor_util.constant_value(summary.op.inputs[0])\n for summary in ops.get_collection(ops.GraphKeys.SUMMARIES)]\n existing_tags = [name.tolist() if isinstance(name, np.ndarray) else name\n for name in existing_tags]\n return tag.encode() not in existing_tags\n\n\ndef summarize_activation(op):\n \"\"\"Summarize an activation.\n\n This applies the given activation and adds useful summaries specific to the\n activation.\n\n Args:\n op: The tensor to summarize (assumed to be a layer activation).\n Returns:\n The summary op created to summarize `op`.\n \"\"\"\n if op.op.type in ('Relu', 'Softplus', 'Relu6'):\n # Using inputs to avoid floating point equality and/or epsilons.\n _add_scalar_summary(\n standard_ops.reduce_mean(standard_ops.to_float(standard_ops.less(\n op.op.inputs[0], standard_ops.cast(0.0, op.op.inputs[0].dtype)))),\n '%s/zeros' % op.op.name)\n if op.op.type == 'Relu6':\n _add_scalar_summary(\n standard_ops.reduce_mean(standard_ops.to_float(standard_ops.greater(\n op.op.inputs[0], standard_ops.cast(6.0, op.op.inputs[0].dtype)))),\n '%s/sixes' % op.op.name)\n return _add_histogram_summary(op, '%s/activation' % op.op.name)\n\n\ndef summarize_tensor(tensor, tag=None):\n \"\"\"Summarize a tensor using a suitable summary type.\n\n This function adds a summary op for `tensor`. The type of summary depends on\n the shape of `tensor`. For scalars, a `scalar_summary` is created, for all\n other tensors, `histogram_summary` is used.\n\n Args:\n tensor: The tensor to summarize\n tag: The tag to use, if None then use tensor's op's name.\n\n Returns:\n The summary op created or None for string tensors.\n \"\"\"\n # Skips string tensors and boolean tensors (not handled by the summaries).\n if (tensor.dtype.is_compatible_with(dtypes.string) or\n tensor.dtype.base_dtype == dtypes.bool):\n return None\n\n if tensor.get_shape().ndims == 0:\n # For scalars, use a scalar summary.\n return _add_scalar_summary(tensor, tag)\n else:\n # We may land in here if the rank is still unknown. The histogram won't\n # hurt if this ends up being a scalar.\n return _add_histogram_summary(tensor, tag)\n\n\ndef summarize_tensors(tensors, summarizer=summarize_tensor):\n \"\"\"Summarize a set of tensors.\"\"\"\n return [summarizer(tensor) for tensor in tensors]\n\n\ndef summarize_collection(collection, name_filter=None,\n summarizer=summarize_tensor):\n \"\"\"Summarize a graph collection of tensors, possibly filtered by name.\"\"\"\n tensors = []\n for op in ops.get_collection(collection):\n if name_filter is None or re.match(name_filter, op.op.name):\n tensors.append(op)\n return summarize_tensors(tensors, summarizer)\n\n\n# Utility functions for commonly used collections\nsummarize_variables = functools.partial(summarize_collection,\n ops.GraphKeys.VARIABLES)\n\n\nsummarize_weights = functools.partial(summarize_collection,\n ops.GraphKeys.WEIGHTS)\n\n\nsummarize_biases = functools.partial(summarize_collection,\n ops.GraphKeys.BIASES)\n\n\ndef summarize_activations(name_filter=None, summarizer=summarize_activation):\n \"\"\"Summarize activations, using `summarize_activation` to summarize.\"\"\"\n return summarize_collection(ops.GraphKeys.ACTIVATIONS, name_filter,\n summarizer)\n", "# pylint: disable=g-bad-file-header\n# 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\"\"\"Removes parts of a graph that are only needed for training.\n\nThere are several common transformations that can be applied to GraphDefs\ncreated to train a model, that help reduce the amount of computation needed when\nthe network is used only for inference. These include:\n\n - Removing training-only operations like checkpoint saving.\n\n - Stripping out parts of the graph that are never reached.\n\n - Removing debug operations like CheckNumerics.\n\n - Folding batch normalization ops into the pre-calculated weights.\n\n - Fusing common operations into unified versions.\n\nThis script takes a frozen GraphDef file (where the weight variables have been\nconverted into constants by the freeze_graph script) and outputs a new GraphDef\nwith the optimizations applied.\n\nAn example of command-line usage is:\n\nbazel build tensorflow/python/tools:optimize_for_inference && \\\nbazel-bin/tensorflow/python/tools/optimize_for_inference \\\n--input_graph=some_graph_def.pb \\\n--output_graph=/tmp/optimized_graph.pb \\\n--input_names=Mul \\\n--output_names=softmax\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport re\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.tools import strip_unused_lib\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\ndef optimize_for_inference(input_graph_def, input_node_names,\n output_node_names, placeholder_type_enum):\n \"\"\"Applies a series of inference optimizations on the input graph.\n\n Args:\n input_graph_def: A GraphDef containing a training model.\n input_node_names: A list of names of the nodes that are fed inputs during\n inference.\n output_node_names: A list of names of the nodes that produce the final\n results.\n placeholder_type_enum: Data type of the placeholders used for inputs.\n\n Returns:\n An optimized version of the input graph.\n \"\"\"\n ensure_graph_is_valid(input_graph_def)\n optimized_graph_def = input_graph_def\n optimized_graph_def = strip_unused_lib.strip_unused(optimized_graph_def,\n input_node_names,\n output_node_names,\n placeholder_type_enum)\n optimized_graph_def = graph_util.remove_training_nodes(optimized_graph_def)\n optimized_graph_def = fold_batch_norms(optimized_graph_def)\n optimized_graph_def = fuse_resize_and_conv(optimized_graph_def)\n ensure_graph_is_valid(optimized_graph_def)\n return optimized_graph_def\n\n\ndef ensure_graph_is_valid(graph_def):\n \"\"\"Makes sure that the graph is internally consistent.\n\n Checks basic properties of the graph def and raises an exception if there are\n input references to missing nodes, duplicated names, or other logic errors.\n\n Args:\n graph_def: Definition of a graph to be checked.\n\n Raises:\n ValueError: If the graph is incorrectly constructed.\n \"\"\"\n node_map = {}\n for node in graph_def.node:\n if node.name not in node_map.keys():\n node_map[node.name] = node\n else:\n raise ValueError(\"Duplicate node names detected for \", node.name)\n for node in graph_def.node:\n for input_name in node.input:\n input_node_name = node_name_from_input(input_name)\n if input_node_name not in node_map.keys():\n raise ValueError(\"Input for \", node.name, \" not found: \", input_name)\n\n\ndef node_name_from_input(node_name):\n \"\"\"Strips off ports and other decorations to get the underlying node name.\"\"\"\n if node_name.startswith(\"^\"):\n node_name = node_name[1:]\n m = re.search(r\"(.*):\\d+$\", node_name)\n if m:\n node_name = m.group(1)\n return node_name\n\n\ndef node_from_map(node_map, name):\n \"\"\"Pulls a node def from a dictionary for a given name.\n\n Args:\n node_map: Dictionary containing an entry indexed by name for every node.\n name: Identifies the node we want to find.\n\n Returns:\n NodeDef of the node with the given name.\n\n Raises:\n ValueError: If the node isn't present in the dictionary.\n \"\"\"\n stripped_name = node_name_from_input(name)\n if stripped_name not in node_map:\n raise ValueError(\"No node named '%s' found in map.\" % name)\n return node_map[stripped_name]\n\n\ndef values_from_const(node_def):\n \"\"\"Extracts the values from a const NodeDef as a numpy ndarray.\n\n Args:\n node_def: Const NodeDef that has the values we want to access.\n\n Returns:\n Numpy ndarray containing the values.\n\n Raises:\n ValueError: If the node isn't a Const.\n \"\"\"\n if node_def.op != \"Const\":\n raise ValueError(\n \"Node named '%s' should be a Const op for values_from_const.\" %\n node_def.name)\n input_tensor = node_def.attr[\"value\"].tensor\n tensor_value = tensor_util.MakeNdarray(input_tensor)\n return tensor_value\n\n\ndef fold_batch_norms(input_graph_def):\n \"\"\"Removes batch normalization ops by folding them into convolutions.\n\n Batch normalization during training has multiple dynamic parameters that are\n updated, but once the graph is finalized these become constants. That means\n there's an opportunity to reduce the computations down to a scale and\n addition, rather than the more expensive multiple ops, and even bake the\n scaling into the convolution weights. This function identifies the typical\n pattern of batch normalization subgraphs, and performs the transformation to\n fold the computations down into a simpler form. It currently only spots batch\n normalization that's performed by the BatchNormWithGlobalNormalization op, and\n will need to be extended in the future to handle the newer style.\n\n Args:\n input_graph_def: A GraphDef containing a model.\n\n Returns:\n Modified graph with BN ops removed, and modified weights.\n\n Raises:\n ValueError: If the graph is badly formed with duplicate node names.\n \"\"\"\n\n input_node_map = {}\n for node in input_graph_def.node:\n if node.name not in input_node_map.keys():\n input_node_map[node.name] = node\n else:\n raise ValueError(\"Duplicate node names detected for \", node.name)\n\n nodes_to_skip = {}\n new_ops = []\n for node in input_graph_def.node:\n if node.op != \"BatchNormWithGlobalNormalization\":\n continue\n\n conv_op = node_from_map(input_node_map, node.input[0])\n if conv_op.op != \"Conv2D\":\n tf.logging.warning(\"Didn't find expected Conv2D input to '%s'\" %\n node.name)\n continue\n\n weights_op = node_from_map(input_node_map, conv_op.input[1])\n if weights_op.op != \"Const\":\n tf.logging.warning(\"Didn't find expected conv Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" %\n (conv_op.name, weights_op))\n continue\n weights = values_from_const(weights_op)\n channel_count = weights.shape[3]\n\n mean_op = node_from_map(input_node_map, node.input[1])\n if mean_op.op != \"Const\":\n tf.logging.warning(\"Didn't find expected mean Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" %\n (node.name, mean_op))\n continue\n mean_value = values_from_const(mean_op)\n if mean_value.shape != (channel_count,):\n tf.logging.warning(\"Incorrect shape for mean, found %s, expected %s,\"\n \" for node %s\" % (str(mean_value.shape),\n str((channel_count,)),\n node.name))\n continue\n\n var_op = node_from_map(input_node_map, node.input[2])\n if var_op.op != \"Const\":\n tf.logging.warning(\"Didn't find expected var Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" %\n (node.name, var_op))\n continue\n var_value = values_from_const(var_op)\n if var_value.shape != (channel_count,):\n tf.logging.warning(\"Incorrect shape for var, found %s, expected %s,\"\n \" for node %s\" % (str(var_value.shape),\n str((channel_count,)),\n node.name))\n continue\n\n beta_op = node_from_map(input_node_map, node.input[3])\n if beta_op.op != \"Const\":\n tf.logging.warning(\"Didn't find expected beta Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" %\n (node.name, beta_op))\n continue\n beta_value = values_from_const(beta_op)\n if beta_value.shape != (channel_count,):\n tf.logging.warning(\"Incorrect shape for beta, found %s, expected %s,\"\n \" for node %s\" % (str(beta_value.shape),\n str((channel_count,)),\n node.name))\n continue\n\n gamma_op = node_from_map(input_node_map, node.input[4])\n if gamma_op.op != \"Const\":\n tf.logging.warning(\"Didn't find expected gamma Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" %\n (node.name, gamma_op))\n continue\n gamma_value = values_from_const(gamma_op)\n if gamma_value.shape != (channel_count,):\n tf.logging.warning(\"Incorrect shape for gamma, found %s, expected %s,\"\n \" for node %s\" % (str(gamma_value.shape),\n str((channel_count,)),\n node.name))\n continue\n\n variance_epsilon_value = node.attr[\"variance_epsilon\"].f\n scale_after_normalization = node.attr[\"scale_after_normalization\"].b\n nodes_to_skip[node.name] = True\n nodes_to_skip[weights_op.name] = True\n nodes_to_skip[mean_op.name] = True\n nodes_to_skip[var_op.name] = True\n nodes_to_skip[beta_op.name] = True\n nodes_to_skip[gamma_op.name] = True\n nodes_to_skip[conv_op.name] = True\n\n if scale_after_normalization:\n scale_value = ((1.0 / np.vectorize(math.sqrt)\n (var_value + variance_epsilon_value)) *\n gamma_value)\n else:\n scale_value = (1.0 / np.vectorize(math.sqrt)\n (var_value + variance_epsilon_value))\n offset_value = (-mean_value * scale_value) + beta_value\n scaled_weights = np.copy(weights)\n it = np.nditer(scaled_weights, flags=[\"multi_index\"],\n op_flags=[\"readwrite\"])\n while not it.finished:\n current_scale = scale_value[it.multi_index[3]]\n it[0] *= current_scale\n it.iternext()\n scaled_weights_op = tf.NodeDef()\n scaled_weights_op.op = \"Const\"\n scaled_weights_op.name = weights_op.name\n scaled_weights_op.attr[\"dtype\"].CopyFrom(weights_op.attr[\"dtype\"])\n scaled_weights_op.attr[\"value\"].CopyFrom(tf.AttrValue(\n tensor=tensor_util.make_tensor_proto(\n scaled_weights, weights.dtype.type, weights.shape)))\n new_conv_op = tf.NodeDef()\n new_conv_op.CopyFrom(conv_op)\n offset_op = tf.NodeDef()\n offset_op.op = \"Const\"\n offset_op.name = conv_op.name + \"_bn_offset\"\n offset_op.attr[\"dtype\"].CopyFrom(mean_op.attr[\"dtype\"])\n offset_op.attr[\"value\"].CopyFrom(tf.AttrValue(\n tensor=tensor_util.make_tensor_proto(\n offset_value, mean_value.dtype.type, offset_value.shape)))\n bias_add_op = tf.NodeDef()\n bias_add_op.op = \"BiasAdd\"\n bias_add_op.name = node.name\n bias_add_op.attr[\"T\"].CopyFrom(conv_op.attr[\"T\"])\n bias_add_op.input.extend([new_conv_op.name, offset_op.name])\n new_ops.extend([scaled_weights_op, new_conv_op, offset_op, bias_add_op])\n\n result_graph_def = tf.GraphDef()\n for node in input_graph_def.node:\n if node.name in nodes_to_skip:\n continue\n new_node = tf.NodeDef()\n new_node.CopyFrom(node)\n result_graph_def.node.extend([new_node])\n\n result_graph_def.node.extend(new_ops)\n return result_graph_def\n\n\ndef fuse_resize_and_conv(input_graph_def):\n \"\"\"Merges preceding resize and mirror pad ops into a specialized convolution.\n\n There's a common pattern of enlarging the input to a convolution using a\n resize operation, and also using MirrorPad to extend the boundaries to that\n zero edge pixels don't bleed inwards when convolving. This routine looks for\n that pattern of operations, and fuses them together into a Conv2DWithResizeOp.\n\n Args:\n input_graph_def: A GraphDef containing a model.\n\n Returns:\n Modified graph with resize and pad ops merged.\n\n Raises:\n ValueError: If the graph is badly formed with duplicate node names.\n \"\"\"\n\n input_node_map = {}\n for node in input_graph_def.node:\n if node.name not in input_node_map.keys():\n input_node_map[node.name] = node\n else:\n raise ValueError(\"Duplicate node names detected for \", node.name)\n\n nodes_to_skip = {}\n new_ops = []\n for node in input_graph_def.node:\n\n if node.op != \"Conv2D\":\n continue\n conv_op = node\n\n input_op = node_from_map(input_node_map, conv_op.input[0])\n if input_op.op == \"MirrorPad\":\n mirror_pad_op = input_op\n resize_op = node_from_map(input_node_map, mirror_pad_op.input[0])\n else:\n mirror_pad_op = None\n resize_op = input_op\n\n if resize_op.op != \"ResizeBilinear\":\n continue\n\n nodes_to_skip[conv_op.name] = True\n if mirror_pad_op:\n nodes_to_skip[mirror_pad_op.name] = True\n nodes_to_skip[resize_op.name] = True\n\n fused_conv_op = tf.NodeDef()\n fused_conv_op.op = \"FusedResizeAndPadConv2D\"\n fused_conv_op.name = conv_op.name\n if mirror_pad_op:\n mirror_paddings_name = mirror_pad_op.input[1]\n mirror_paddings_mode = mirror_pad_op.attr[\"mode\"]\n else:\n # If there was no MirrorPad op, then create settings that make the padding\n # stage of the fused operation a no-op.\n paddings_op = tf.NodeDef()\n paddings_op.op = \"Const\"\n paddings_op.name = conv_op.name + \"_dummy_paddings\"\n paddings_op.attr[\"dtype\"].CopyFrom(tf.AttrValue(\n type=tf.int32.as_datatype_enum))\n paddings_op.attr[\"value\"].CopyFrom(tf.AttrValue(\n tensor=tensor_util.make_tensor_proto(\n [0, 0, 0, 0, 0, 0, 0, 0], tf.int32, [4, 2])))\n new_ops.extend([paddings_op])\n mirror_paddings_name = paddings_op.name\n mirror_paddings_mode = tf.AttrValue(s=b\"REFLECT\")\n fused_conv_op.input.extend([resize_op.input[0], resize_op.input[1],\n mirror_paddings_name, conv_op.input[1]])\n fused_conv_op.attr[\"T\"].CopyFrom(conv_op.attr[\"T\"])\n fused_conv_op.attr[\"resize_align_corners\"].CopyFrom(\n resize_op.attr[\"align_corners\"])\n fused_conv_op.attr[\"mode\"].CopyFrom(mirror_paddings_mode)\n fused_conv_op.attr[\"strides\"].CopyFrom(conv_op.attr[\"strides\"])\n fused_conv_op.attr[\"padding\"].CopyFrom(conv_op.attr[\"padding\"])\n new_ops.extend([fused_conv_op])\n\n result_graph_def = tf.GraphDef()\n for node in input_graph_def.node:\n if node.name in nodes_to_skip:\n continue\n new_node = tf.NodeDef()\n new_node.CopyFrom(node)\n result_graph_def.node.extend([new_node])\n\n result_graph_def.node.extend(new_ops)\n return result_graph_def\n" ]
[ [ "tensorflow.python.summary.impl.gcs_file_loader.GCSFileLoader", "tensorflow.python.platform.gfile.Walk", "tensorflow.python.platform.gfile.ListDirectory", "tensorflow.python.summary.impl.gcs.IsDirectory", "tensorflow.python.summary.impl.gcs.IsGCSPath", "tensorflow.python.summary.impl.event_file_loader.EventFileLoader", "tensorflow.python.platform.gfile.Exists", "tensorflow.python.summary.impl.gcs.ListRecursively", "tensorflow.python.platform.gfile.IsDirectory", "tensorflow.python.summary.impl.gcs.Exists", "tensorflow.python.platform.gfile.Open", "tensorflow.python.summary.impl.gcs.ListDirectory" ], [ "tensorflow.python.ops.array_ops.matrix_set_diag", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.array_ops.shape", "tensorflow.contrib.distributions.python.ops.distribution_util.assert_integer_form", "tensorflow.python.ops.check_ops.assert_positive", "tensorflow.python.ops.special_math_ops.lbeta", "tensorflow.python.ops.check_ops.assert_equal", "tensorflow.python.framework.ops.name_scope", "tensorflow.contrib.distributions.python.ops.distribution_util.log_combinations", "tensorflow.contrib.distributions.python.ops.distribution_util.append_class_fun_doc", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.check_ops.assert_non_negative", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ops.check_ops.assert_rank_at_least" ], [ "tensorflow.gfile.DeleteRecursively", "tensorflow.gfile.Exists", "numpy.random.randint", "tensorflow.Variable", "tensorflow.merge_all_summaries", "tensorflow.test.main", "tensorflow.python.platform.gfile.MakeDirs", "tensorflow.initialize_all_variables", "numpy.argmax", "tensorflow.train.summary_iterator", "tensorflow.train.Saver", "tensorflow.argmax", "tensorflow.contrib.metrics.streaming_accuracy", "tensorflow.train.string_input_producer", "numpy.random.rand", "numpy.sum", "tensorflow.constant", "numpy.random.seed", "tensorflow.initialize_local_variables", "tensorflow.scalar_summary", "tensorflow.mul", "tensorflow.train.SummaryWriter", "numpy.ones" ], [ "tensorflow.initialize_all_tables", "tensorflow.zeros", "tensorflow.contrib.layers.python.layers.feature_column_ops._Transformer", "tensorflow.contrib.layers.weighted_sparse_column", "tensorflow.contrib.layers.weighted_sum_from_feature_columns", "tensorflow.contrib.layers.bucketized_column", "tensorflow.Graph", "tensorflow.contrib.layers.input_from_feature_columns", "tensorflow.contrib.layers.sparse_column_with_keys", "tensorflow.get_collection", "tensorflow.contrib.layers.joint_weighted_sum_from_feature_columns", "tensorflow.gradients", "tensorflow.test.main", "tensorflow.truncated_normal_initializer", "tensorflow.contrib.layers.one_hot_column", "tensorflow.contrib.layers.crossed_column", "tensorflow.initialize_all_variables", "tensorflow.trainable_variables", "tensorflow.shape", "tensorflow.min_max_variable_partitioner", "tensorflow.train.FloatList", "tensorflow.train.BytesList", "tensorflow.contrib.layers.sparse_column_with_hash_bucket", "tensorflow.constant", "numpy.tile", "tensorflow.contrib.layers.real_valued_column", "tensorflow.SparseTensor", "tensorflow.constant_initializer", "tensorflow.contrib.layers.sparse_column_with_integerized_feature", "tensorflow.contrib.layers.embedding_column", "tensorflow.contrib.layers.hashed_embedding_column" ], [ "tensorflow.core.protobuf.config_pb2.RunMetadata", "numpy.asarray", "tensorflow.core.protobuf.config_pb2.GraphOptions", "tensorflow.core.protobuf.config_pb2.RunOptions", "tensorflow.python.client.session.InteractiveSession", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.array_ops.sparse_placeholder", "tensorflow.python.ops.array_ops.zeros", "numpy.iinfo", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.array_ops.identity", "numpy.random.randint", "tensorflow.python.framework.ops.IndexedSlicesValue", "tensorflow.python.framework.ops._default_session_stack.reset", "tensorflow.python.framework.ops.IndexedSlices", "tensorflow.python.ops.math_ops.add", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.platform.googletest.main", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.framework.ops.SparseTensor", "tensorflow.python.framework.ops.RegisterShape", "tensorflow.python.ops.math_ops.mul", "tensorflow.python.framework.ops.SparseTensorValue", "tensorflow.python.client.session.Session", "numpy.array", "tensorflow.python.ops.data_flow_ops.FIFOQueue", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.framework.ops._default_session_stack.get_default", "tensorflow.python.framework.ops.Graph", "numpy.ones", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.array_ops.reshape", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.framework.constant_op.constant" ], [ "numpy.sqrt", "tensorflow.Variable", "numpy.isfinite", "tensorflow.zeros", "numpy.arange", "tensorflow.gradients", "tensorflow.test.main", "tensorflow.ones", "numpy.ones", "scipy.stats.norm", "tensorflow.initialize_all_variables", "numpy.random.RandomState" ], [ "tensorflow.contrib.cudnn_rnn.CudnnLSTM", "tensorflow.test.compute_gradient_error", "tensorflow.Graph", "tensorflow.reduce_sum", "tensorflow.test.is_built_with_cuda", "tensorflow.contrib.cudnn_rnn.CudnnGRU", "tensorflow.ones", "tensorflow.initialize_all_variables", "tensorflow.python.platform.googletest.main", "tensorflow.set_random_seed", "tensorflow.contrib.cudnn_rnn.CudnnRNNRelu", "tensorflow.random_uniform", "tensorflow.contrib.cudnn_rnn.CudnnRNNTanh" ], [ "tensorflow.contrib.framework.print_op", "tensorflow.constant", "tensorflow.TensorArray", "tensorflow.sparse_tensor_to_dense", "tensorflow.test.main", "tensorflow.SparseTensor" ], [ "tensorflow.get_default_session", "tensorflow.train.AdagradOptimizer", "tensorflow.constant", "tensorflow.Variable", "tensorflow.test.main", "tensorflow.initialize_all_variables", "tensorflow.train.GradientDescentOptimizer", "tensorflow.train.FtrlOptimizer", "numpy.array" ], [ "numpy.random.rand", "numpy.array", "tensorflow.test.main", "numpy.random.seed" ], [ "tensorflow.python.ops.standard_ops.histogram_summary", "tensorflow.python.framework.ops.get_collection", "tensorflow.python.ops.standard_ops.scalar_summary", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.ops.standard_ops.cast" ], [ "tensorflow.python.framework.graph_util.remove_training_nodes", "tensorflow.python.framework.tensor_util.MakeNdarray", "tensorflow.logging.warning", "tensorflow.python.tools.strip_unused_lib.strip_unused", "numpy.nditer", "numpy.copy", "numpy.vectorize", "tensorflow.python.framework.tensor_util.make_tensor_proto", "tensorflow.GraphDef", "tensorflow.AttrValue", "tensorflow.NodeDef" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "0.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "0.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ahoneybun/tensorflow
[ "51100a8de57ef53e36a8a9f5a9829cbd33fbed04", "5134e65300d1ac384eeb1f4ca72a011ad7225bc8", "5134e65300d1ac384eeb1f4ca72a011ad7225bc8", "5134e65300d1ac384eeb1f4ca72a011ad7225bc8" ]
[ "tensorflow/python/keras/engine/training.py", "tensorflow/python/keras/applications/imagenet_utils_test.py", "tensorflow/compiler/tests/eager_test.py", "tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer.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# ==============================================================================\n\"\"\"Training-related part of the Keras engine.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport weakref\nimport numpy as np\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import losses\nfrom tensorflow.python.keras import metrics as metrics_module\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.engine import base_layer\nfrom tensorflow.python.keras.engine import distributed_training_utils\nfrom tensorflow.python.keras.engine import training_arrays\nfrom tensorflow.python.keras.engine import training_distributed\nfrom tensorflow.python.keras.engine import training_eager\nfrom tensorflow.python.keras.engine import training_generator\nfrom tensorflow.python.keras.engine import training_utils\nfrom tensorflow.python.keras.engine.network import Network\nfrom tensorflow.python.keras.utils.generic_utils import slice_arrays\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import weights_broadcast_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import optimizer as tf_optimizer_module\nfrom tensorflow.python.training.checkpointable import base as checkpointable\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export('keras.models.Model', 'keras.Model')\nclass Model(Network):\n \"\"\"`Model` groups layers into an object with training and inference features.\n\n There are two ways to instantiate a `Model`:\n\n 1 - With the \"functional API\", where you start from `Input`,\n you chain layer calls to specify the model's forward pass,\n and finally you create your model from inputs and outputs:\n\n ```python\n import tensorflow as tf\n\n inputs = tf.keras.Input(shape=(3,))\n x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)\n outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\n ```\n\n 2 - By subclassing the `Model` class: in that case, you should define your\n layers in `__init__` and you should implement the model's forward pass\n in `call`.\n\n ```python\n import tensorflow as tf\n\n class MyModel(tf.keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)\n\n def call(self, inputs):\n x = self.dense1(inputs)\n return self.dense2(x)\n\n model = MyModel()\n ```\n\n If you subclass `Model`, you can optionally have\n a `training` argument (boolean) in `call`, which you can use to specify\n a different behavior in training and inference:\n\n ```python\n import tensorflow as tf\n\n class MyModel(tf.keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)\n self.dropout = tf.keras.layers.Dropout(0.5)\n\n def call(self, inputs, training=False):\n x = self.dense1(inputs)\n if training:\n x = self.dropout(x, training=training)\n return self.dense2(x)\n\n model = MyModel()\n ```\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(Model, self).__init__(*args, **kwargs)\n # Create a cache for iterator get_next op.\n self._iterator_get_next = weakref.WeakKeyDictionary()\n # Create a cache for dataset - uninitialized iterators\n self._dataset_iterator_cache = weakref.WeakKeyDictionary()\n # initializing _distribution_strategy here since it is possible to call\n # predict on a model without compiling it.\n self._distribution_strategy = None\n\n def _set_sample_weight_attributes(self, sample_weight_mode,\n skip_target_weighing_indices):\n \"\"\"Sets sample weight related attributes on the model.\"\"\"\n sample_weights, sample_weight_modes = training_utils.prepare_sample_weights(\n self.output_names, sample_weight_mode, skip_target_weighing_indices)\n self.sample_weights = sample_weights\n self.sample_weight_modes = sample_weight_modes\n self._feed_sample_weight_modes = [\n sample_weight_modes[i]\n for i in range(len(self.outputs))\n if i not in skip_target_weighing_indices\n ]\n self._feed_sample_weights = [\n sample_weights[i]\n for i in range(len(sample_weights))\n if i not in skip_target_weighing_indices\n ]\n\n def _get_metric_name(self, metric, output_index, weighted=False):\n \"\"\"Returns the metric name corresponding to the given metric input.\n\n Arguments:\n metric: Metric function name or reference.\n output_index: Index of the current output.\n weighted: Boolean indicating if the given metric is weighted.\n\n Returns:\n A metric name.\n \"\"\"\n metric_name_prefix = 'weighted_' if weighted else ''\n if metric in ('accuracy', 'acc', 'crossentropy', 'ce'):\n if metric in ('accuracy', 'acc'):\n suffix = 'acc'\n elif metric in ('crossentropy', 'ce'):\n suffix = 'ce'\n else:\n metric_fn = metrics_module.get(metric)\n # Get metric name as string\n if hasattr(metric_fn, 'name'):\n suffix = metric_fn.name\n else:\n suffix = metric_fn.__name__\n metric_name = metric_name_prefix + suffix\n\n if len(self.output_names) > 1:\n metric_name = '%s_%s' % (self.output_names[output_index], metric_name)\n j = 1\n base_metric_name = metric_name\n while metric_name in self.metrics_names:\n metric_name = '%s_%d' % (base_metric_name, j)\n j += 1\n\n return metric_name\n\n def _handle_per_output_metrics(self,\n metrics,\n y_true,\n y_pred,\n output_index,\n output_shape,\n loss_fn,\n mask,\n weights=None):\n \"\"\"Calls metric functions and sets metric attributes for a single output.\n\n Arguments:\n metrics: List of metrics.\n y_true: Target output.\n y_pred: Predicted output.\n output_index: Index of the current output.\n output_shape: Shape of the current output.\n loss_fn: Loss function corresponding to the current output.\n mask: Computed mask value for the current output.\n weights: Weights to be applied on the current output.\n\n Returns:\n A list of metric result tensors.\n \"\"\"\n metric_results = []\n for metric in metrics:\n metric_fn = training_utils.get_metric_function(\n metric, output_shape=output_shape, loss_fn=loss_fn)\n metric_name = self._get_metric_name(\n metric, output_index, weighted=weights is not None)\n\n with K.name_scope(metric_name):\n # If both outputs and targets are available, call the metric function.\n if y_true is not None and y_pred is not None:\n if isinstance(metric_fn, metrics_module.Metric):\n # Call the stateful metric function.\n if mask is not None:\n mask = math_ops.cast(mask, y_pred.dtype)\n # Update weights with mask.\n if weights is None:\n weights = mask\n else:\n # Update shape of weights if possible before adding mask.\n # Update dimensions of weights to match with mask if possible.\n mask, _, weights = metrics_module.squeeze_or_expand_dimensions(\n mask, None, weights)\n try:\n # Broadcast weights if possible.\n weights = weights_broadcast_ops.broadcast_weights(\n weights, mask)\n except ValueError:\n pass\n # TODO(psv): Handle case when mask and weight shapes are not\n # compatible.\n weights *= mask\n\n metric_result = metric_fn(y_true, y_pred, weights)\n else:\n # Call the stateless metric function.\n weighted_metric_fn = training_utils.weighted_masked_objective(\n metric_fn)\n metric_result = weighted_metric_fn(\n y_true, y_pred, weights=weights, mask=mask)\n\n if not context.executing_eagerly():\n # Keep track of metric result tensor.\n self.metrics_tensors.append(metric_result)\n metric_results.append(metric_result)\n\n # Keep track of metric name.\n self.metrics_names.append(metric_name)\n\n # Keep track of stateful metric attributes (name and metric function).\n if isinstance(metric_fn, base_layer.Layer) and metric_fn.stateful:\n self.stateful_metric_names.append(metric_name)\n self.stateful_metric_functions.append(metric_fn)\n if not context.executing_eagerly():\n # Keep track of updates created by stateful metrics.\n self.metrics_updates += metric_fn.updates\n return metric_results\n\n def _handle_metrics(self,\n outputs,\n skip_target_indices=None,\n targets=None,\n sample_weights=None,\n masks=None):\n \"\"\"Handles calling metric functions and setting model metric attributes.\n\n Arguments:\n outputs: List of outputs (predictions).\n skip_target_indices: Optional. List of target ids to skip.\n targets: List of targets.\n sample_weights: Optional list of sample weight arrays.\n masks: List of computed output mask values.\n\n Returns:\n A list of metric result tensors.\n \"\"\"\n skip_target_indices = skip_target_indices or []\n metric_results = []\n with K.name_scope('metrics'):\n for i in range(len(outputs)):\n if i in skip_target_indices:\n continue\n output = outputs[i] if outputs else None\n target = targets[i] if targets else None\n output_shape = None if output is None else output.get_shape().as_list()\n output_mask = masks[i] if masks else None\n metric_results.extend(\n self._handle_per_output_metrics(\n self.nested_metrics[i], target, output, i, output_shape,\n self.loss_functions[i], output_mask))\n metric_results.extend(\n self._handle_per_output_metrics(\n self.nested_weighted_metrics[i],\n target,\n output,\n i,\n output_shape,\n self.loss_functions[i],\n output_mask,\n weights=sample_weights[i]))\n return metric_results\n\n @checkpointable.no_automatic_dependency_tracking\n def compile(self,\n optimizer,\n loss=None,\n metrics=None,\n loss_weights=None,\n sample_weight_mode=None,\n weighted_metrics=None,\n target_tensors=None,\n distribute=None,\n **kwargs):\n \"\"\"Configures the model for training.\n\n Arguments:\n optimizer: String (name of optimizer) or optimizer instance.\n See [optimizers](/api_docs/python/tf/keras/optimizers).\n loss: String (name of objective function) or objective function.\n See [losses](/api_docs/python/tf/losses).\n If the model has multiple outputs, you can use a different loss\n on each output by passing a dictionary or a list of losses.\n The loss value that will be minimized by the model\n will then be the sum of all individual losses.\n metrics: List of metrics to be evaluated by the model\n during training and testing.\n Typically you will use `metrics=['accuracy']`.\n To specify different metrics for different outputs of a\n multi-output model, you could also pass a dictionary,\n such as `metrics={'output_a': 'accuracy'}`.\n loss_weights: Optional list or dictionary specifying scalar\n coefficients (Python floats) to weight the loss contributions\n of different model outputs.\n The loss value that will be minimized by the model\n will then be the *weighted sum* of all individual losses,\n weighted by the `loss_weights` coefficients.\n If a list, it is expected to have a 1:1 mapping\n to the model's outputs. If a tensor, it is expected to map\n output names (strings) to scalar coefficients.\n sample_weight_mode: If you need to do timestep-wise\n sample weighting (2D weights), set this to `\"temporal\"`.\n `None` defaults to sample-wise weights (1D).\n If the model has multiple outputs, you can use a different\n `sample_weight_mode` on each output by passing a\n dictionary or a list of modes.\n weighted_metrics: List of metrics to be evaluated and weighted\n by sample_weight or class_weight during training and testing.\n target_tensors: By default, Keras will create placeholders for the\n model's target, which will be fed with the target data during\n training. If instead you would like to use your own\n target tensors (in turn, Keras will not expect external\n Numpy data for these targets at training time), you\n can specify them via the `target_tensors` argument. It can be\n a single tensor (for a single-output model), a list of tensors,\n or a dict mapping output names to target tensors.\n distribute: The DistributionStrategy instance that we want to use to\n distribute the training of the model.\n **kwargs: These arguments are passed to `tf.Session.run`.\n\n Raises:\n ValueError: In case of invalid arguments for\n `optimizer`, `loss`, `metrics` or `sample_weight_mode`.\n \"\"\"\n # Validate that arguments passed by the user to `compile` are supported by\n # DistributionStrategy.\n if distribute and not isinstance(\n optimizer, (tf_optimizer_module.Optimizer, optimizers.TFOptimizer)):\n raise NotImplementedError('Only TF native optimizers are supported with '\n 'DistributionStrategy.')\n if distribute and context.executing_eagerly():\n raise NotImplementedError('DistributionStrategy is not supported in '\n 'Eager mode.')\n if distribute and sample_weight_mode:\n raise NotImplementedError('sample_weight_mode is not supported with '\n 'DistributionStrategy.')\n if distribute and weighted_metrics:\n raise NotImplementedError('weighted_metrics is not supported with '\n 'DistributionStrategy.')\n if distribute and target_tensors:\n raise ValueError('target_tensors is not supported with '\n 'DistributionStrategy.')\n\n loss = loss or {}\n if context.executing_eagerly() and not isinstance(\n optimizer, (tf_optimizer_module.Optimizer, optimizers.TFOptimizer)):\n raise ValueError('Only TF native optimizers are supported in Eager mode.')\n\n self.optimizer = optimizers.get(optimizer)\n # We've disabled automatic dependency tracking for this method, but do want\n # to add a checkpoint dependency on the optimizer if it's checkpointable.\n if isinstance(self.optimizer, checkpointable.CheckpointableBase):\n self._track_checkpointable(\n self.optimizer, name='optimizer', overwrite=True)\n self.loss = loss\n self.metrics = metrics or []\n self.loss_weights = loss_weights\n self.sample_weight_mode = sample_weight_mode\n self.weighted_metrics = weighted_metrics\n if context.executing_eagerly() and target_tensors is not None:\n raise ValueError('target_tensors is not supported in Eager mode.')\n self.target_tensors = target_tensors\n\n # Set DistributionStrategy specific parameters.\n self._distribution_strategy = distribute\n if self._distribution_strategy is not None:\n self._grouped_model = self._compile_distributed_model(\n self._distribution_strategy)\n with self._distribution_strategy.scope():\n first_replicated_model = self._distribution_strategy.unwrap(\n self._grouped_model)[0]\n # If the specified metrics in `compile` are stateful, raise an error\n # since we currently don't support stateful metrics.\n if first_replicated_model.stateful_metric_names:\n raise NotImplementedError('Stateful metrics are not supported with '\n 'DistributionStrategy.')\n\n # We initialize the callback model with the first replicated model.\n self._replicated_model = DistributedCallbackModel(first_replicated_model)\n self._replicated_model.set_original_model(self)\n if not self.built:\n # Model is not compilable because it does not know its number of inputs\n # and outputs, nor their shapes and names. We will compile after the first\n # time the model gets called on training data.\n return\n self._is_compiled = True\n\n # Prepare loss functions.\n if isinstance(loss, dict):\n for name in loss:\n if name not in self.output_names:\n raise ValueError(\n 'Unknown entry in loss '\n 'dictionary: \"' + name + '\". '\n 'Only expected the following keys: ' + str(self.output_names))\n loss_functions = []\n for name in self.output_names:\n if name not in loss:\n logging.warning(\n 'Output \"' + name + '\" missing from loss dictionary. We assume '\n 'this was done on purpose. The fit and evaluate APIs will not be '\n 'expecting any data to be passed to \"' + name + '\".')\n loss_functions.append(losses.get(loss.get(name)))\n elif isinstance(loss, list):\n if len(loss) != len(self.outputs):\n raise ValueError('When passing a list as loss, '\n 'it should have one entry per model outputs. '\n 'The model has ' + str(len(self.outputs)) +\n ' outputs, but you passed loss=' + str(loss))\n loss_functions = [losses.get(l) for l in loss]\n else:\n loss_function = losses.get(loss)\n loss_functions = [loss_function for _ in range(len(self.outputs))]\n self.loss_functions = loss_functions\n\n weighted_losses = [training_utils.weighted_masked_objective(fn)\n for fn in loss_functions]\n skip_target_indices = []\n skip_target_weighing_indices = []\n self._feed_outputs = []\n self._feed_output_names = []\n self._feed_output_shapes = []\n self._feed_loss_fns = []\n for i in range(len(weighted_losses)):\n if weighted_losses[i] is None:\n skip_target_indices.append(i)\n skip_target_weighing_indices.append(i)\n\n # Prepare output masks.\n if not context.executing_eagerly():\n masks = [getattr(x, '_keras_mask', None) for x in self.outputs]\n if not isinstance(masks, list):\n masks = [masks]\n\n # Prepare loss weights.\n if loss_weights is None:\n loss_weights_list = [1. for _ in range(len(self.outputs))]\n elif isinstance(loss_weights, dict):\n for name in loss_weights:\n if name not in self.output_names:\n raise ValueError(\n 'Unknown entry in loss_weights '\n 'dictionary: \"' + name + '\". '\n 'Only expected the following keys: ' + str(self.output_names))\n loss_weights_list = []\n for name in self.output_names:\n loss_weights_list.append(loss_weights.get(name, 1.))\n elif isinstance(loss_weights, list):\n if len(loss_weights) != len(self.outputs):\n raise ValueError(\n 'When passing a list as loss_weights, '\n 'it should have one entry per model output. '\n 'The model has ' + str(len(self.outputs)) +\n ' outputs, but you passed loss_weights=' + str(loss_weights))\n loss_weights_list = loss_weights\n else:\n raise TypeError('Could not interpret loss_weights argument: ' +\n str(loss_weights) + ' - expected a list of dicts.')\n self.loss_weights_list = loss_weights_list\n\n # Initialize model metric attributes.\n self.metrics_names = ['loss']\n self.metrics_tensors = []\n self.metrics_updates = []\n self.stateful_metric_names = []\n self.stateful_metric_functions = []\n\n # Nested metrics is a list of list of metrics.\n # One list per output of the model.\n self.nested_metrics = training_utils.collect_metrics(\n metrics, self.output_names)\n self.nested_weighted_metrics = training_utils.collect_metrics(\n weighted_metrics, self.output_names)\n\n # Initialization for Eager mode execution.\n if context.executing_eagerly():\n # Prepare sample weights.\n self._set_sample_weight_attributes(sample_weight_mode,\n skip_target_weighing_indices)\n\n if target_tensors is not None:\n raise ValueError('target_tensors are not currently supported in Eager '\n 'mode.')\n self.total_loss = None\n for i in range(len(self.outputs)):\n if len(self.outputs) > 1:\n self.metrics_names.append(self.output_names[i] + '_loss')\n\n # Set metric attributes on model.\n self._handle_metrics(\n self.outputs,\n skip_target_indices=skip_target_indices,\n sample_weights=self.sample_weights)\n\n self.targets = []\n for i in range(len(self.outputs)):\n self._feed_output_names.append(self.output_names[i])\n self._collected_trainable_weights = self.trainable_weights\n return\n\n # Prepare targets of model.\n self.targets = []\n self._feed_targets = []\n if target_tensors not in (None, []):\n if isinstance(target_tensors, list):\n if len(target_tensors) != len(self.outputs):\n raise ValueError(\n 'When passing a list as `target_tensors`, '\n 'it should have one entry per model output. '\n 'The model has ' + str(len(self.outputs)) +\n ' outputs, but you passed target_tensors=' + str(target_tensors))\n elif isinstance(target_tensors, dict):\n for name in target_tensors:\n if name not in self.output_names:\n raise ValueError(\n 'Unknown entry in `target_tensors` '\n 'dictionary: \"' + name + '\". '\n 'Only expected the following keys: ' + str(self.output_names))\n tmp_target_tensors = []\n for name in self.output_names:\n tmp_target_tensors.append(target_tensors.get(name, None))\n target_tensors = tmp_target_tensors\n else:\n raise TypeError('Expected `target_tensors` to be '\n 'a list or dict, but got:', target_tensors)\n\n for i in range(len(self.outputs)):\n if i in skip_target_indices:\n self.targets.append(None)\n else:\n shape = K.int_shape(self.outputs[i])\n name = self.output_names[i]\n if target_tensors not in (None, []):\n target = target_tensors[i]\n else:\n target = None\n if target is None or K.is_placeholder(target):\n if target is None:\n target = K.placeholder(\n ndim=len(shape),\n name=name + '_target',\n sparse=K.is_sparse(self.outputs[i]),\n dtype=K.dtype(self.outputs[i]))\n self._feed_targets.append(target)\n self._feed_outputs.append(self.outputs[i])\n self._feed_output_names.append(name)\n self._feed_output_shapes.append(shape)\n self._feed_loss_fns.append(self.loss_functions[i])\n else:\n skip_target_weighing_indices.append(i)\n self.targets.append(target)\n\n # Prepare sample weights.\n self._set_sample_weight_attributes(sample_weight_mode,\n skip_target_weighing_indices)\n\n # Compute total loss.\n total_loss = None\n with K.name_scope('loss'):\n for i in range(len(self.outputs)):\n if i in skip_target_indices:\n continue\n y_true = self.targets[i]\n y_pred = self.outputs[i]\n weighted_loss = weighted_losses[i]\n sample_weight = self.sample_weights[i]\n mask = masks[i]\n loss_weight = loss_weights_list[i]\n with K.name_scope(self.output_names[i] + '_loss'):\n output_loss = weighted_loss(y_true, y_pred, sample_weight, mask)\n if len(self.outputs) > 1:\n self.metrics_tensors.append(output_loss)\n self.metrics_names.append(self.output_names[i] + '_loss')\n if total_loss is None:\n total_loss = loss_weight * output_loss\n else:\n total_loss += loss_weight * output_loss\n if total_loss is None:\n if not self.losses:\n raise ValueError('The model cannot be compiled '\n 'because it has no loss to optimize.')\n else:\n total_loss = 0.\n\n # Add regularization penalties\n # and other layer-specific losses.\n for loss_tensor in self.losses:\n total_loss += loss_tensor\n\n # Invoke metric functions for all the outputs.\n self._handle_metrics(\n self.outputs,\n masks=masks,\n targets=self.targets,\n skip_target_indices=skip_target_indices,\n sample_weights=self.sample_weights)\n\n # Prepare gradient updates and state updates.\n self.total_loss = total_loss\n\n # Functions for train, test and predict will\n # be compiled lazily when required.\n # This saves time when the user is not using all functions.\n self._function_kwargs = kwargs\n\n self.train_function = None\n self.test_function = None\n self.predict_function = None\n\n # Collected trainable weights, sorted in topological order.\n trainable_weights = self.trainable_weights\n self._collected_trainable_weights = trainable_weights\n\n def _compile_distributed_model(self, distribution_strategy):\n # TODO(anjalisridhar): Can we move the clone_and_build_model to outside the\n # model?\n def _clone_model_per_tower(model):\n new_model = training_distributed.clone_and_build_model(model)\n return new_model\n\n with distribution_strategy.scope():\n # Create a copy of this model on each of the devices.\n grouped_models = distribution_strategy.call_for_each_tower(\n _clone_model_per_tower, self)\n return grouped_models\n\n def _check_trainable_weights_consistency(self):\n \"\"\"Check trainable weights count consistency.\n\n This will raise a warning if `trainable_weights` and\n `_collected_trainable_weights` are inconsistent (i.e. have different\n number of parameters).\n Inconsistency will typically arise when one modifies `model.trainable`\n without calling `model.compile` again.\n \"\"\"\n if not hasattr(self, '_collected_trainable_weights'):\n return\n\n if len(self.trainable_weights) != len(self._collected_trainable_weights):\n logging.warning(\n UserWarning(\n 'Discrepancy between trainable weights and collected trainable'\n ' weights, did you set `model.trainable` without calling'\n ' `model.compile` after ?'))\n\n def _make_train_function(self):\n if not hasattr(self, 'train_function'):\n raise RuntimeError('You must compile your model before using it.')\n self._check_trainable_weights_consistency()\n if self.train_function is None:\n inputs = (self._feed_inputs +\n self._feed_targets +\n self._feed_sample_weights)\n if self.uses_learning_phase and not isinstance(K.learning_phase(), int):\n inputs += [K.learning_phase()]\n\n with K.name_scope('training'):\n with K.name_scope(self.optimizer.__class__.__name__):\n # Training updates\n updates = self.optimizer.get_updates(\n params=self._collected_trainable_weights, loss=self.total_loss)\n # Unconditional updates\n updates += self.get_updates_for(None)\n # Conditional updates relevant to this model\n updates += self.get_updates_for(self.inputs)\n # Stateful metrics updates\n updates += self.metrics_updates\n # Gets loss and metrics. Updates weights at each call.\n self.train_function = K.function(\n inputs, [self.total_loss] + self.metrics_tensors,\n updates=updates,\n name='train_function',\n **self._function_kwargs)\n\n def _make_test_function(self):\n if not hasattr(self, 'test_function'):\n raise RuntimeError('You must compile your model before using it.')\n if self.test_function is None:\n inputs = (self._feed_inputs +\n self._feed_targets +\n self._feed_sample_weights)\n if self.uses_learning_phase and not isinstance(K.learning_phase(), int):\n inputs += [K.learning_phase()]\n # Return loss and metrics, no gradient updates.\n # Does update the network states.\n self.test_function = K.function(\n inputs, [self.total_loss] + self.metrics_tensors,\n updates=self.state_updates + self.metrics_updates,\n name='test_function',\n **self._function_kwargs)\n\n def _make_predict_function(self):\n if not hasattr(self, 'predict_function'):\n self.predict_function = None\n if self.predict_function is None:\n if self.uses_learning_phase and not isinstance(K.learning_phase(), int):\n inputs = self._feed_inputs + [K.learning_phase()]\n else:\n inputs = self._feed_inputs\n # Gets network outputs. Does not update weights.\n # Does update the network states.\n kwargs = getattr(self, '_function_kwargs', {})\n self.predict_function = K.function(\n inputs,\n self.outputs,\n updates=self.state_updates,\n name='predict_function',\n **kwargs)\n\n def _get_iterator_get_next_tensors(self, iterator):\n get_next_op = self._iterator_get_next.get(iterator, None)\n if get_next_op is None:\n get_next_op = iterator.get_next()\n self._iterator_get_next[iterator] = get_next_op\n return get_next_op\n\n def _distribution_standardize_user_data(self,\n x,\n y=None,\n sample_weight=None,\n class_weight=None,\n batch_size=None,\n check_steps=False,\n steps_name='steps',\n steps=None,\n validation_split=0):\n \"\"\"Runs validation checks on input and target data passed by the user.\n\n This is called when using DistributionStrategy to train, evaluate or serve\n the model.\n\n Args:\n x: Input data. A `tf.data` dataset.\n y: Since `x` is a dataset, `y` should not be specified\n (since targets will be obtained from the iterator).\n sample_weight: An optional sample-weight array passed by the user to\n weight the importance of each sample in `x`.\n class_weight: An optional class-weight array by the user to\n weight the importance of samples in `x` based on the class they belong\n to, as conveyed by `y`.\n batch_size: Integer batch size. If provided, it is used to run additional\n validation checks on stateful models.\n check_steps: boolean, True if we want to check for validity of `steps` and\n False, otherwise.\n steps_name: The public API's parameter name for `steps`.\n steps: Integer or `None`. Total number of steps (batches of samples) to\n execute.\n validation_split: Float between 0 and 1.\n Fraction of the training data to be used as validation data.\n\n Returns:\n A tuple of 3 lists: input arrays, target arrays, sample-weight arrays.\n If the model's input and targets are symbolic, these lists are empty\n (since the model takes no user-provided data, instead the data comes\n from the symbolic inputs/targets).\n\n Raises:\n ValueError: In case of invalid user-provided data.\n RuntimeError: If the model was never compiled.\n \"\"\"\n if sample_weight is not None and sample_weight.all():\n raise NotImplementedError('sample_weight is currently not supported when '\n 'using DistributionStrategy.')\n if class_weight:\n raise NotImplementedError('class_weight is currently not supported when '\n 'using DistributionStrategy.')\n\n # TODO(anjalisridhar): Can we use the iterator and getnext op cache?\n # We require users to pass Datasets since we distribute the dataset across\n # multiple devices.\n if not isinstance(x, dataset_ops.Dataset):\n raise ValueError('When using DistributionStrategy you must specify a '\n 'Dataset object instead of a %s.' % type(x))\n # TODO(anjalisridhar): We want distribute_dataset() to accept a Dataset or a\n # function which returns a Dataset. Currently distribute_dataset() only\n # accepts a function that returns a Dataset. Once we add support for being\n # able to clone a Dataset on multiple workers we can remove this lambda.\n result = self._distribution_strategy.distribute_dataset(lambda: x)\n iterator = result.make_initializable_iterator()\n K.get_session().run(iterator.initializer)\n # Validates `steps` argument based on x's type.\n if check_steps:\n if steps is None:\n raise ValueError('When using a Dataset instance as input to a model, '\n 'you should specify the `{steps_name}` argument.'\n .format(steps_name=steps_name))\n\n training_utils.validate_iterator_input(x, y, sample_weight,\n validation_split)\n # x an y may be PerDevice objects with an input and output tensor\n # corresponding to each device. For example, x could be\n # PerDevice:{device: get_next tensor,...}.\n next_element = iterator.get_next()\n\n if not isinstance(next_element, (list, tuple)) or len(next_element) != 2:\n raise ValueError('Please provide data as a list or tuple of 2 elements '\n ' - input and target pair. Received %s' % next_element)\n x, y = next_element\n # Validate that all the elements in x and y are of the same type and shape.\n # We can then pass the first element of x and y to `_standardize_weights`\n # below and be confident of the output. We need to reopen the scope since\n # we unwrap values when we validate x and y.\n with self._distribution_strategy.scope():\n x_values, y_values = distributed_training_utils.\\\n validate_distributed_dataset_inputs(self._distribution_strategy, x, y)\n\n _, _, sample_weights = self._standardize_weights(x_values,\n y_values,\n sample_weight,\n class_weight,\n batch_size)\n return x, y, sample_weights\n\n def _standardize_user_data(self,\n x,\n y=None,\n sample_weight=None,\n class_weight=None,\n batch_size=None,\n check_steps=False,\n steps_name='steps',\n steps=None,\n validation_split=0):\n \"\"\"Runs validation checks on input and target data passed by the user.\n\n Also standardizes the data to lists of arrays, in order.\n\n Also builds and compiles the model on the fly if it is a subclassed model\n that has never been called before (and thus has no inputs/outputs).\n\n This is a purely internal method, subject to refactoring at any time.\n\n Args:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset or a dataset iterator.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset or a\n dataset iterator, `y` should not be specified\n (since targets will be obtained from the iterator).\n sample_weight: An optional sample-weight array passed by the user to\n weight the importance of each sample in `x`.\n class_weight: An optional class-weight array by the user to\n weight the importance of samples in `x` based on the class they belong\n to, as conveyed by `y`.\n batch_size: Integer batch size. If provided, it is used to run additional\n validation checks on stateful models.\n check_steps: boolean, True if we want to check for validity of `steps` and\n False, otherwise. For example, when we are standardizing one batch of\n data for train_on_batch/predict_on_batch/test_on_batch APIs, `steps`\n value is not required and we should not check for its validity in these\n cases.\n steps_name: The public API's parameter name for `steps`.\n steps: Integer or `None`. Total number of steps (batches of samples) to\n execute.\n validation_split: Float between 0 and 1.\n Fraction of the training data to be used as validation data.\n\n Returns:\n A tuple of 3 lists: input arrays, target arrays, sample-weight arrays.\n If the model's input and targets are symbolic, these lists are empty\n (since the model takes no user-provided data, instead the data comes\n from the symbolic inputs/targets).\n\n Raises:\n ValueError: In case of invalid user-provided data.\n RuntimeError: If the model was never compiled.\n \"\"\"\n if self._distribution_strategy:\n return self._distribution_standardize_user_data(\n x,\n y,\n sample_weight=sample_weight,\n class_weight=class_weight,\n batch_size=batch_size,\n check_steps=check_steps,\n steps_name=steps_name,\n steps=steps,\n validation_split=validation_split)\n\n if isinstance(x, dataset_ops.Dataset):\n if context.executing_eagerly():\n x = x.make_one_shot_iterator()\n else:\n if x in self._dataset_iterator_cache:\n x = self._dataset_iterator_cache[x]\n else:\n iterator = x.make_initializable_iterator()\n self._dataset_iterator_cache[x] = iterator\n x = iterator\n K.get_session().run(x.initializer)\n\n # Validates `steps` argument based on x's type.\n if check_steps:\n training_utils.check_steps_argument(x, steps, steps_name)\n\n is_x_eager_iterator = isinstance(x, iterator_ops.EagerIterator)\n is_x_iterator = isinstance(x, iterator_ops.Iterator)\n\n # Validate user inputs when data is given as a dataset or dataset iterator.\n if is_x_iterator or is_x_eager_iterator:\n training_utils.validate_iterator_input(x, y, sample_weight,\n validation_split)\n\n # For eager iterators, when we have to process multiple batches of samples,\n # we will standardize the data when we actually loop over iterator and get\n # the batches. For now, we just return the iterator as is.\n if is_x_eager_iterator and steps is not None:\n return x, y, sample_weight\n\n # If input data is a dataset iterator in graph mode or if it is an eager\n # iterator and only one batch of samples is required, we fetch the data\n # tensors from the iterator and then standardize them.\n if is_x_iterator or is_x_eager_iterator:\n try:\n if is_x_iterator:\n next_element = self._get_iterator_get_next_tensors(x)\n else:\n next_element = x.get_next()\n except errors.OutOfRangeError:\n raise RuntimeError('Your dataset iterator ran out of data; '\n 'Make sure that your dataset can generate '\n 'required number of samples.')\n\n if not isinstance(next_element, (list, tuple)) or len(next_element) != 2:\n raise ValueError('Please provide data as a list or tuple of 2 elements '\n ' - input and target pair. Received %s' % next_element)\n x, y = next_element\n x, y, sample_weights = self._standardize_weights(x, y, sample_weight,\n class_weight, batch_size)\n return x, y, sample_weights\n\n def _standardize_weights(self, x, y, sample_weight=None, class_weight=None,\n batch_size=None,):\n # First, we build/compile the model on the fly if necessary.\n all_inputs = []\n is_build_called = False\n is_compile_called = False\n if not self.inputs:\n # We need to use `x` to set the model inputs.\n # We type-check that `x` and `y` are either single arrays\n # or lists of arrays.\n if isinstance(x, (list, tuple)):\n if not all(isinstance(v, np.ndarray) or\n tensor_util.is_tensor(v) for v in x):\n raise ValueError('Please provide as model inputs either a single '\n 'array or a list of arrays. You passed: x=' + str(x))\n all_inputs += list(x)\n elif isinstance(x, dict):\n raise ValueError('Please do not pass a dictionary as model inputs.')\n else:\n if not isinstance(x, np.ndarray) and not tensor_util.is_tensor(x):\n raise ValueError('Please provide as model inputs either a single '\n 'array or a list of arrays. You passed: x=' + str(x))\n all_inputs.append(x)\n\n # Build the model using the retrieved inputs (value or symbolic).\n # If values, then in symbolic-mode placeholders will be created\n # to match the value shapes.\n if not self.inputs:\n is_build_called = True\n self._set_inputs(x)\n\n if y is not None:\n if not self.optimizer:\n raise RuntimeError('You must compile a model before '\n 'training/testing. '\n 'Use `model.compile(optimizer, loss)`.')\n if not self._is_compiled:\n # On-the-fly compilation of the model.\n # We need to use `y` to set the model targets.\n if isinstance(y, (list, tuple)):\n if not all(isinstance(v, np.ndarray) or\n tensor_util.is_tensor(v) for v in y):\n raise ValueError('Please provide as model targets either a single '\n 'array or a list of arrays. '\n 'You passed: y=' + str(y))\n all_inputs += list(y)\n elif isinstance(y, dict):\n raise ValueError('Please do not pass a dictionary as model targets.')\n else:\n if not isinstance(y, np.ndarray) and not tensor_util.is_tensor(y):\n raise ValueError('Please provide as model targets either a single '\n 'array or a list of arrays. '\n 'You passed: y=' + str(y))\n all_inputs.append(y)\n\n # Typecheck that all inputs are *either* value *or* symbolic.\n # TODO(fchollet): this check could be removed in Eager mode?\n if any(tensor_util.is_tensor(v) for v in all_inputs):\n if not all(tensor_util.is_tensor(v) for v in all_inputs):\n raise ValueError('Do not pass inputs that mix Numpy arrays and '\n 'TensorFlow tensors. '\n 'You passed: x=' + str(x) + '; y=' + str(y))\n\n if context.executing_eagerly():\n target_tensors = None\n else:\n # Handle target tensors if any passed.\n if not isinstance(y, (list, tuple)):\n y = [y]\n target_tensors = [v for v in y if tensor_util.is_tensor(v)]\n is_compile_called = True\n self.compile(optimizer=self.optimizer,\n loss=self.loss,\n metrics=self.metrics,\n loss_weights=self.loss_weights,\n target_tensors=target_tensors)\n\n # In graph mode, if we had just set inputs and targets as symbolic tensors\n # by invoking build and compile on the model respectively, we do not have to\n # feed anything to the model. Model already has input and target data as\n # part of the graph.\n # Note: in this case, `any` and `all` are equivalent since we disallow\n # mixed symbolic/value inputs.\n if (not context.executing_eagerly() and is_build_called and\n is_compile_called and\n any(tensor_util.is_tensor(v) for v in all_inputs)):\n return [], [], []\n\n # What follows is input validation and standardization to list format,\n # in the case where all inputs are value arrays.\n\n if context.executing_eagerly():\n # In eager mode, do not do shape validation\n # since the network has no input nodes (placeholders) to be fed.\n feed_input_names = self.input_names\n feed_input_shapes = None\n elif not self._is_graph_network:\n # Case: symbolic-mode subclassed network. Do not do shape validation.\n feed_input_names = self._feed_input_names\n feed_input_shapes = None\n else:\n # Case: symbolic-mode graph network.\n # In this case, we run extensive shape validation checks.\n feed_input_names = self._feed_input_names\n feed_input_shapes = self._feed_input_shapes\n\n # Standardize the inputs.\n x = training_utils.standardize_input_data(\n x,\n feed_input_names,\n feed_input_shapes,\n check_batch_axis=False, # Don't enforce the batch size.\n exception_prefix='input')\n\n if y is not None:\n if not self._is_graph_network:\n feed_output_names = self._feed_output_names\n feed_output_shapes = None\n # Sample weighting not supported in this case.\n # TODO(fchollet): consider supporting it.\n feed_sample_weight_modes = [None for _ in self.outputs]\n else:\n feed_output_names = self._feed_output_names\n feed_sample_weight_modes = self._feed_sample_weight_modes\n feed_output_shapes = []\n for output_shape, loss_fn in zip(self._feed_output_shapes,\n self._feed_loss_fns):\n if loss_fn is losses.sparse_categorical_crossentropy:\n if K.image_data_format() == 'channels_first':\n feed_output_shapes.append(\n (output_shape[0], 1) + output_shape[2:])\n else:\n feed_output_shapes.append(output_shape[:-1] + (1,))\n elif (not hasattr(loss_fn, '__name__') or\n getattr(losses, loss_fn.__name__, None) is None):\n # If `loss_fn` is not a function (e.g. callable class)\n # or if it not in the `losses` module, then\n # it is a user-defined loss and we make no assumptions\n # about it.\n feed_output_shapes.append(None)\n else:\n feed_output_shapes.append(output_shape)\n\n # Standardize the outputs.\n y = training_utils.standardize_input_data(\n y,\n feed_output_names,\n feed_output_shapes,\n check_batch_axis=False, # Don't enforce the batch size.\n exception_prefix='target')\n\n # Generate sample-wise weight values given the `sample_weight` and\n # `class_weight` arguments.\n sample_weights = training_utils.standardize_sample_weights(\n sample_weight, feed_output_names)\n class_weights = training_utils.standardize_class_weights(\n class_weight, feed_output_names)\n sample_weights = [\n training_utils.standardize_weights(ref, sw, cw, mode)\n for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,\n feed_sample_weight_modes)\n ]\n # Check that all arrays have the same length.\n if not self._distribution_strategy:\n training_utils.check_array_lengths(x, y, sample_weights)\n if self._is_graph_network and not context.executing_eagerly():\n # Additional checks to avoid users mistakenly using improper loss fns.\n training_utils.check_loss_and_target_compatibility(\n y, self._feed_loss_fns, feed_output_shapes)\n else:\n y = []\n sample_weights = []\n\n if self.stateful and batch_size:\n # Check that for stateful networks, number of samples is a multiple\n # of the static batch size.\n if x[0].shape[0] % batch_size != 0:\n raise ValueError('In a stateful network, '\n 'you should only pass inputs with '\n 'a number of samples that can be '\n 'divided by the batch size. Found: ' +\n str(x[0].shape[0]) + ' samples')\n return x, y, sample_weights\n\n @checkpointable.no_automatic_dependency_tracking\n def _set_inputs(self, inputs, training=None):\n \"\"\"Set model's input and output specs based on the input data received.\n\n This is to be used for Model subclasses, which do not know at instantiation\n time what their inputs look like.\n\n Args:\n inputs: Single array, or list of arrays. The arrays could be placeholders,\n Numpy arrays, or data tensors.\n - if placeholders: the model is built on top of these placeholders,\n and we expect Numpy data to be fed for them when calling `fit`/etc.\n - if Numpy data: we create placeholders matching the shape of the Numpy\n arrays. We expect Numpy data to be fed for these placeholders\n when calling `fit`/etc.\n - if data tensors: the model is built on top of these tensors.\n We do not expect any Numpy data to be provided when calling `fit`/etc.\n training: Boolean or None. Only relevant in symbolic mode. Specifies\n whether to build the model's graph in inference mode (False), training\n mode (True), or using the Keras learning phase (None).\n \"\"\"\n call_convention = getattr(\n self,\n '_call_convention',\n base_layer.CallConvention.EXPLICIT_INPUTS_ARGUMENT)\n if call_convention not in (\n base_layer.CallConvention.EXPLICIT_INPUTS_ARGUMENT,\n base_layer.CallConvention.SINGLE_POSITIONAL_ARGUMENT):\n raise NotImplementedError(\n 'Subclassed Models without \"inputs\" (or single positional arguments) '\n 'in their call() signatures do not yet support shape inference. File '\n 'a feature request if this limitation bothers you.')\n if self.__class__.__name__ == 'Sequential':\n if tensor_util.is_tensor(inputs):\n input_shape = (None,) + tuple(inputs.get_shape().as_list()[1:])\n self.build(input_shape=input_shape)\n else:\n input_shape = (None,) + inputs.shape[1:]\n self.build(input_shape=input_shape)\n if context.executing_eagerly():\n self._eager_set_inputs(inputs)\n else:\n self._symbolic_set_inputs(inputs, training=training)\n\n @checkpointable.no_automatic_dependency_tracking\n def _eager_set_inputs(self, inputs):\n \"\"\"Set model's input and output specs based on the input data received.\n\n This is to be used for Model subclasses, which do not know at instantiation\n time what their inputs look like.\n\n We assume the number and ndim of outputs\n does not change over different calls.\n\n Args:\n inputs: Argument `x` (input data) passed by the user upon first model use.\n\n Raises:\n ValueError: If the model's inputs are already set.\n \"\"\"\n assert context.executing_eagerly()\n if self.inputs:\n raise ValueError('Model inputs are already set.')\n # On-the-fly setting of model inputs/outputs as DeferredTensors,\n # to keep track of number of inputs and outputs and their ndim.\n if isinstance(inputs, (list, tuple)):\n if tensor_util.is_tensor(inputs[0]):\n dummy_output_values = self.call(\n training_utils.cast_if_floating_dtype(inputs))\n else:\n dummy_output_values = self.call(\n [ops.convert_to_tensor(v, dtype=K.floatx()) for v in inputs])\n dummy_input_values = list(inputs)\n else:\n if tensor_util.is_tensor(inputs):\n dummy_output_values = self.call(\n training_utils.cast_if_floating_dtype(inputs))\n else:\n dummy_output_values = self.call(\n ops.convert_to_tensor(inputs, dtype=K.floatx()))\n dummy_input_values = [inputs]\n if isinstance(dummy_output_values, (list, tuple)):\n dummy_output_values = list(dummy_output_values)\n else:\n dummy_output_values = [dummy_output_values]\n self.outputs = [\n base_layer.DeferredTensor(shape=(None for _ in v.shape),\n dtype=v.dtype) for v in dummy_output_values]\n self.inputs = [\n base_layer.DeferredTensor(shape=(None for _ in v.shape),\n dtype=v.dtype) for v in dummy_input_values]\n self.input_names = [\n 'input_%d' % (i + 1) for i in range(len(dummy_input_values))]\n self.output_names = [\n 'output_%d' % (i + 1) for i in range(len(dummy_output_values))]\n self.built = True\n\n @checkpointable.no_automatic_dependency_tracking\n def _symbolic_set_inputs(self, inputs, outputs=None, training=None):\n \"\"\"Set model's inputs and output specs based.\n\n This is to be used for Model subclasses, which do not know at instantiation\n time what their inputs look like.\n\n Args:\n inputs: Argument `x` (input data) passed by the user upon first model use.\n outputs: None, a data tensor, or a list of data tensors. If None, the\n outputs will be determined by invoking self.call(), otherwise the\n provided value will be used.\n training: Boolean or None. Only relevant in symbolic mode. Specifies\n whether to build the model's graph in inference mode (False), training\n mode (True), or using the Keras learning phase (None).\n\n Raises:\n ValueError: If the model's inputs are already set.\n \"\"\"\n assert not context.executing_eagerly()\n if self.inputs:\n raise ValueError('Model inputs are already set.')\n\n # On-the-fly setting of symbolic model inputs (either by using the tensor\n # provided, or by creating a placeholder if Numpy data was provided).\n self.inputs = []\n self.input_names = []\n self._feed_inputs = []\n self._feed_input_names = []\n self._feed_input_shapes = []\n if isinstance(inputs, (list, tuple)):\n inputs = list(inputs)\n else:\n inputs = [inputs]\n\n for i, v in enumerate(inputs):\n name = 'input_%d' % (i + 1)\n self.input_names.append(name)\n if isinstance(v, list):\n v = np.asarray(v)\n if v.ndim == 1:\n v = np.expand_dims(v, 1)\n if isinstance(v, (np.ndarray)):\n # We fix the placeholder shape except the batch size.\n # This is suboptimal, but it is the best we can do with the info\n # we have. The user should call `model._set_inputs(placeholders)`\n # to specify custom placeholders if the need arises.\n shape = (None,) + v.shape[1:]\n placeholder = K.placeholder(shape=shape, name=name)\n self.inputs.append(placeholder)\n self._feed_inputs.append(placeholder)\n self._feed_input_names.append(name)\n self._feed_input_shapes.append(shape)\n else:\n # Assumed tensor - TODO(fchollet) additional type check?\n self.inputs.append(v)\n if K.is_placeholder(v):\n self._feed_inputs.append(v)\n self._feed_input_names.append(name)\n self._feed_input_shapes.append(K.int_shape(v))\n\n if outputs is None:\n # Obtain symbolic outputs by calling the model.\n if len(self.inputs) == 1:\n if self._expects_training_arg:\n outputs = self.call(self.inputs[0], training=training)\n else:\n outputs = self.call(self.inputs[0])\n else:\n if self._expects_training_arg:\n outputs = self.call(self.inputs, training=training)\n else:\n outputs = self.call(self.inputs)\n if isinstance(outputs, (list, tuple)):\n outputs = list(outputs)\n else:\n outputs = [outputs]\n self.outputs = outputs\n self.output_names = [\n 'output_%d' % (i + 1) for i in range(len(self.outputs))]\n self.built = True\n\n def fit(self,\n x=None,\n y=None,\n batch_size=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_split=0.,\n validation_data=None,\n shuffle=True,\n class_weight=None,\n sample_weight=None,\n initial_epoch=0,\n steps_per_epoch=None,\n validation_steps=None,\n **kwargs):\n \"\"\"Trains the model for a fixed number of epochs (iterations on a dataset).\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset or a dataset iterator.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset or dataset\n iterator, `y` should not be specified\n (since targets will be obtained from the iterator).\n batch_size: Integer or `None`.\n Number of samples per gradient update.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` if your data is in the\n form of symbolic tensors, datasets, or dataset iterators\n (since they generate batches).\n epochs: Integer. Number of epochs to train the model.\n An epoch is an iteration over the entire `x` and `y`\n data provided.\n Note that in conjunction with `initial_epoch`,\n `epochs` is to be understood as \"final epoch\".\n The model is not trained for a number of iterations\n given by `epochs`, but merely until the epoch\n of index `epochs` is reached.\n verbose: Integer. 0, 1, or 2. Verbosity mode.\n 0 = silent, 1 = progress bar, 2 = one line per epoch.\n callbacks: List of `keras.callbacks.Callback` instances.\n List of callbacks to apply during training.\n See [callbacks](/api_docs/python/tf/keras/callbacks).\n validation_split: Float between 0 and 1.\n Fraction of the training data to be used as validation data.\n The model will set apart this fraction of the training data,\n will not train on it, and will evaluate\n the loss and any model metrics\n on this data at the end of each epoch.\n The validation data is selected from the last samples\n in the `x` and `y` data provided, before shuffling. This argument is\n not supported when `x` is a dataset or a dataset iterator.\n validation_data: Data on which to evaluate\n the loss and any model metrics at the end of each epoch.\n The model will not be trained on this data.\n `validation_data` will override `validation_split`.\n `validation_data` could be:\n - tuple `(x_val, y_val)` of Numpy arrays or tensors\n - tuple `(x_val, y_val, val_sample_weights)` of Numpy arrays\n - dataset or a dataset iterator\n shuffle: Boolean (whether to shuffle the training data\n before each epoch) or str (for 'batch').\n 'batch' is a special option for dealing with the\n limitations of HDF5 data; it shuffles in batch-sized chunks.\n Has no effect when `steps_per_epoch` is not `None`.\n class_weight: Optional dictionary mapping class indices (integers)\n to a weight (float) value, used for weighting the loss function\n (during training only).\n This can be useful to tell the model to\n \"pay more attention\" to samples from\n an under-represented class.\n sample_weight: Optional Numpy array of weights for\n the training samples, used for weighting the loss function\n (during training only). You can either pass a flat (1D)\n Numpy array with the same length as the input samples\n (1:1 mapping between weights and samples),\n or in the case of temporal data,\n you can pass a 2D array with shape\n `(samples, sequence_length)`,\n to apply a different weight to every timestep of every sample.\n In this case you should make sure to specify\n `sample_weight_mode=\"temporal\"` in `compile()`. This argument is not\n supported when `x` is a dataset or a dataset iterator.\n initial_epoch: Integer.\n Epoch at which to start training\n (useful for resuming a previous training run).\n steps_per_epoch: Integer or `None`.\n Total number of steps (batches of samples)\n before declaring one epoch finished and starting the\n next epoch. When training with input tensors such as\n TensorFlow data tensors, the default `None` is equal to\n the number of samples in your dataset divided by\n the batch size, or 1 if that cannot be determined.\n validation_steps: Only relevant if `steps_per_epoch`\n is specified. Total number of steps (batches of samples)\n to validate before stopping.\n **kwargs: Used for backwards compatibility.\n\n Returns:\n A `History` object. Its `History.history` attribute is\n a record of training loss values and metrics values\n at successive epochs, as well as validation loss values\n and validation metrics values (if applicable).\n\n Raises:\n RuntimeError: If the model was never compiled.\n ValueError: In case of mismatch between the provided input data\n and what the model expects.\n \"\"\"\n # TODO(fchollet): this method may be creating reference cycles, which would\n # lead to accumulating garbage in memory when called in a loop. Investigate.\n\n # Backwards compatibility\n if batch_size is None and steps_per_epoch is None:\n batch_size = 32\n # Legacy support\n if 'nb_epoch' in kwargs:\n logging.warning(\n 'The `nb_epoch` argument in `fit` '\n 'has been renamed `epochs`.')\n epochs = kwargs.pop('nb_epoch')\n if kwargs:\n raise TypeError('Unrecognized keyword arguments: ' + str(kwargs))\n\n # Validate and standardize user data.\n if self._distribution_strategy:\n distributed_training_utils.validate_callbacks(callbacks)\n\n x, y, sample_weights = self._standardize_user_data(\n x,\n y,\n sample_weight=sample_weight,\n class_weight=class_weight,\n batch_size=batch_size,\n check_steps=True,\n steps_name='steps_per_epoch',\n steps=steps_per_epoch,\n validation_split=validation_split)\n\n # Prepare validation data.\n if validation_data:\n if (isinstance(validation_data, iterator_ops.Iterator) or\n isinstance(validation_data, iterator_ops.EagerIterator) or\n isinstance(validation_data, dataset_ops.Dataset)):\n val_x = validation_data\n val_y = None\n val_sample_weight = None\n elif len(validation_data) == 2:\n val_x, val_y = validation_data # pylint: disable=unpacking-non-sequence\n val_sample_weight = None\n elif len(validation_data) == 3:\n val_x, val_y, val_sample_weight = validation_data # pylint: disable=unpacking-non-sequence\n else:\n raise ValueError(\n 'When passing a `validation_data` argument, '\n 'it must contain either 2 items (x_val, y_val), '\n 'or 3 items (x_val, y_val, val_sample_weights), '\n 'or alternatively it could be a dataset or a '\n 'dataset or a dataset iterator. '\n 'However we received `validation_data=%s`' % validation_data)\n\n # Validate and standardize validation data.\n val_x, val_y, val_sample_weights = self._standardize_user_data(\n val_x,\n val_y,\n sample_weight=val_sample_weight,\n batch_size=batch_size,\n steps=validation_steps)\n\n elif validation_split and 0. < validation_split < 1.:\n if training_utils.has_symbolic_tensors(x):\n raise ValueError('If your data is in the form of symbolic tensors, '\n 'you cannot use `validation_split`.')\n if hasattr(x[0], 'shape'):\n split_at = int(x[0].shape[0] * (1. - validation_split))\n else:\n split_at = int(len(x[0]) * (1. - validation_split))\n x, val_x = (slice_arrays(x, 0, split_at), slice_arrays(x, split_at))\n y, val_y = (slice_arrays(y, 0, split_at), slice_arrays(y, split_at))\n sample_weights, val_sample_weights = (slice_arrays(\n sample_weights, 0, split_at), slice_arrays(sample_weights, split_at))\n elif validation_steps:\n val_x = []\n val_y = []\n val_sample_weights = []\n else:\n val_x = None\n val_y = None\n val_sample_weights = None\n\n if context.executing_eagerly():\n return training_eager.fit_loop(\n self,\n inputs=x,\n targets=y,\n sample_weights=sample_weights,\n class_weight=class_weight,\n batch_size=batch_size,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n val_inputs=val_x,\n val_targets=val_y,\n val_sample_weights=val_sample_weights,\n shuffle=shuffle,\n initial_epoch=initial_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_steps=validation_steps)\n elif self._distribution_strategy:\n return training_distributed.fit_loop(\n self, x, y,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n val_inputs=val_x,\n val_targets=val_y,\n initial_epoch=initial_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_steps=validation_steps)\n else:\n return training_arrays.fit_loop(\n self, x, y,\n sample_weights=sample_weights,\n batch_size=batch_size,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n val_inputs=val_x,\n val_targets=val_y,\n val_sample_weights=val_sample_weights,\n shuffle=shuffle,\n initial_epoch=initial_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_steps=validation_steps)\n\n def evaluate(self,\n x=None,\n y=None,\n batch_size=None,\n verbose=1,\n sample_weight=None,\n steps=None):\n \"\"\"Returns the loss value & metrics values for the model in test mode.\n\n Computation is done in batches.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset or a dataset iterator.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely).\n If `x` is a dataset or a dataset iterator, `y` should not be specified\n (since targets will be obtained from the iterator/dataset).\n batch_size: Integer or `None`.\n Number of samples per gradient update.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` is your data is in the\n form of symbolic tensors, datasets, or dataset iterators\n (since they generate batches).\n verbose: 0 or 1. Verbosity mode.\n 0 = silent, 1 = progress bar.\n sample_weight: Optional Numpy array of weights for\n the test samples, used for weighting the loss function.\n You can either pass a flat (1D)\n Numpy array with the same length as the input samples\n (1:1 mapping between weights and samples),\n or in the case of temporal data,\n you can pass a 2D array with shape\n `(samples, sequence_length)`,\n to apply a different weight to every timestep of every sample.\n In this case you should make sure to specify\n `sample_weight_mode=\"temporal\"` in `compile()`. This argument is not\n supported when `x` is a dataset or a dataset iterator.\n steps: Integer or `None`.\n Total number of steps (batches of samples)\n before declaring the evaluation round finished.\n Ignored with the default value of `None`.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: in case of invalid arguments.\n \"\"\"\n # Backwards compatibility.\n if batch_size is None and steps is None:\n batch_size = 32\n\n # Validate and standardize user data.\n x, y, sample_weights = self._standardize_user_data(\n x,\n y,\n sample_weight=sample_weight,\n batch_size=batch_size,\n check_steps=True,\n steps_name='steps',\n steps=steps)\n\n if context.executing_eagerly():\n return training_eager.test_loop(\n self,\n inputs=x,\n targets=y,\n sample_weights=sample_weights,\n batch_size=batch_size,\n verbose=verbose,\n steps=steps)\n elif self._distribution_strategy:\n return training_distributed.test_loop(\n self,\n inputs=x,\n targets=y,\n verbose=verbose,\n steps=steps)\n else:\n return training_arrays.test_loop(\n self,\n inputs=x,\n targets=y,\n sample_weights=sample_weights,\n batch_size=batch_size,\n verbose=verbose,\n steps=steps)\n\n def predict(self, x, batch_size=None, verbose=0, steps=None):\n \"\"\"Generates output predictions for the input samples.\n\n Computation is done in batches.\n\n Arguments:\n x: Input samples. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A `tf.data` dataset or a dataset iterator.\n batch_size: Integer or `None`.\n Number of samples per gradient update.\n If unspecified, `batch_size` will default to 32.\n Do not specify the `batch_size` is your data is in the\n form of symbolic tensors, dataset, or dataset iterators\n (since they generate batches).\n verbose: Verbosity mode, 0 or 1.\n steps: Total number of steps (batches of samples)\n before declaring the prediction round finished.\n Ignored with the default value of `None`.\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case of mismatch between the provided\n input data and the model's expectations,\n or in case a stateful model receives a number of samples\n that is not a multiple of the batch size.\n \"\"\"\n # Backwards compatibility.\n if batch_size is None and steps is None:\n batch_size = 32\n\n # Validate and standardize user data.\n x, _, _ = self._standardize_user_data(\n x, check_steps=True, steps_name='steps', steps=steps)\n\n if context.executing_eagerly():\n return training_eager.predict_loop(\n self, x, batch_size=batch_size, verbose=verbose, steps=steps)\n elif self._distribution_strategy:\n return training_distributed.predict_loop(\n self, x, verbose=verbose, steps=steps)\n else:\n return training_arrays.predict_loop(\n self, x, batch_size=batch_size, verbose=verbose, steps=steps)\n\n def train_on_batch(self, x, y=None, sample_weight=None, class_weight=None):\n \"\"\"Runs a single gradient update on a single batch of data.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset or a dataset iterator.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset or a\n dataset iterator, `y` should not be specified\n (since targets will be obtained from the iterator).\n sample_weight: Optional array of the same length as x, containing\n weights to apply to the model's loss for each sample.\n In the case of temporal data, you can pass a 2D array\n with shape (samples, sequence_length),\n to apply a different weight to every timestep of every sample.\n In this case you should make sure to specify\n sample_weight_mode=\"temporal\" in compile(). This argument is not\n supported when `x` is a dataset or a dataset iterator.\n class_weight: Optional dictionary mapping\n class indices (integers) to\n a weight (float) to apply to the model's loss for the samples\n from this class during training.\n This can be useful to tell the model to \"pay more attention\" to\n samples from an under-represented class.\n\n Returns:\n Scalar training loss\n (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: In case of invalid user-provided arguments.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`train_on_batch` is not supported for models '\n 'compiled with DistributionStrategy.')\n # Validate and standardize user data.\n x, y, sample_weights = self._standardize_user_data(\n x, y, sample_weight=sample_weight, class_weight=class_weight)\n\n if context.executing_eagerly():\n outputs = training_eager.train_on_batch(\n self, x, y, sample_weights=sample_weights)\n else:\n if self.uses_learning_phase and not isinstance(K.learning_phase(), int):\n ins = x + y + sample_weights + [1]\n else:\n ins = x + y + sample_weights\n\n self._make_train_function()\n outputs = self.train_function(ins)\n\n if len(outputs) == 1:\n return outputs[0]\n return outputs\n\n def test_on_batch(self, x, y=None, sample_weight=None):\n \"\"\"Test the model on a single batch of samples.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A dict mapping input names to the corresponding array/tensors,\n if the model has named inputs.\n - A `tf.data` dataset or a dataset iterator.\n y: Target data. Like the input data `x`,\n it could be either Numpy array(s) or TensorFlow tensor(s).\n It should be consistent with `x` (you cannot have Numpy inputs and\n tensor targets, or inversely). If `x` is a dataset or a\n dataset iterator, `y` should not be specified\n (since targets will be obtained from the iterator).\n sample_weight: Optional array of the same length as x, containing\n weights to apply to the model's loss for each sample.\n In the case of temporal data, you can pass a 2D array\n with shape (samples, sequence_length),\n to apply a different weight to every timestep of every sample.\n In this case you should make sure to specify\n sample_weight_mode=\"temporal\" in compile(). This argument is not\n supported when `x` is a dataset or a dataset iterator.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: In case of invalid user-provided arguments.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`test_on_batch` is not supported for models '\n 'compiled with DistributionStrategy.')\n # Validate and standardize user data.\n x, y, sample_weights = self._standardize_user_data(\n x, y, sample_weight=sample_weight)\n\n if context.executing_eagerly():\n outputs = training_eager.test_on_batch(\n self, x, y, sample_weights=sample_weights)\n else:\n if self.uses_learning_phase and not isinstance(K.learning_phase(), int):\n ins = x + y + sample_weights + [0]\n else:\n ins = x + y + sample_weights\n self._make_test_function()\n outputs = self.test_function(ins)\n\n if len(outputs) == 1:\n return outputs[0]\n return outputs\n\n def predict_on_batch(self, x):\n \"\"\"Returns predictions for a single batch of samples.\n\n Arguments:\n x: Input data. It could be:\n - A Numpy array (or array-like), or a list of arrays\n (in case the model has multiple inputs).\n - A TensorFlow tensor, or a list of tensors\n (in case the model has multiple inputs).\n - A `tf.data` dataset or a dataset iterator.\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case of mismatch between given number of inputs and\n expectations of the model.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`predict_on_batch` is not supported for '\n 'models compiled with DistributionStrategy.')\n # Validate and standardize user data.\n inputs, _, _ = self._standardize_user_data(x)\n if context.executing_eagerly():\n if (isinstance(x, iterator_ops.EagerIterator) or\n (isinstance(x, dataset_ops.Dataset) and context.executing_eagerly())):\n inputs = training_utils.cast_if_floating_dtype(inputs)\n else:\n inputs = [\n ops.convert_to_tensor(val, dtype=K.floatx()) for val in inputs\n ]\n return self(inputs) # pylint: disable=not-callable\n\n if not context.executing_eagerly():\n if self.uses_learning_phase and not isinstance(K.learning_phase(), int):\n ins = inputs + [0]\n else:\n ins = inputs\n\n self._make_predict_function()\n outputs = self.predict_function(ins)\n\n if len(outputs) == 1:\n return outputs[0]\n return outputs\n\n def fit_generator(self,\n generator,\n steps_per_epoch=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_data=None,\n validation_steps=None,\n class_weight=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n shuffle=True,\n initial_epoch=0):\n \"\"\"Fits the model on data yielded batch-by-batch by a Python generator.\n\n The generator is run in parallel to the model, for efficiency.\n For instance, this allows you to do real-time data augmentation\n on images on CPU in parallel to training your model on GPU.\n\n The use of `keras.utils.Sequence` guarantees the ordering\n and guarantees the single use of every input per epoch when\n using `use_multiprocessing=True`.\n\n Arguments:\n generator: A generator or an instance of `Sequence`\n (`keras.utils.Sequence`)\n object in order to avoid duplicate data\n when using multiprocessing.\n The output of the generator must be either\n - a tuple `(inputs, targets)`\n - a tuple `(inputs, targets, sample_weights)`.\n This tuple (a single output of the generator) makes a single batch.\n Therefore, all arrays in this tuple must have the same length (equal\n to the size of this batch). Different batches may have different\n sizes.\n For example, the last batch of the epoch is commonly smaller than\n the\n others, if the size of the dataset is not divisible by the batch\n size.\n The generator is expected to loop over its data\n indefinitely. An epoch finishes when `steps_per_epoch`\n batches have been seen by the model.\n steps_per_epoch: Total number of steps (batches of samples)\n to yield from `generator` before declaring one epoch\n finished and starting the next epoch. It should typically\n be equal to the number of samples of your dataset\n divided by the batch size.\n Optional for `Sequence`: if unspecified, will use\n the `len(generator)` as a number of steps.\n epochs: Integer, total number of iterations on the data.\n verbose: Verbosity mode, 0, 1, or 2.\n callbacks: List of callbacks to be called during training.\n validation_data: This can be either\n - a generator for the validation data\n - a tuple (inputs, targets)\n - a tuple (inputs, targets, sample_weights).\n validation_steps: Only relevant if `validation_data`\n is a generator. Total number of steps (batches of samples)\n to yield from `generator` before stopping.\n Optional for `Sequence`: if unspecified, will use\n the `len(validation_data)` as a number of steps.\n class_weight: Dictionary mapping class indices to a weight\n for the class.\n max_queue_size: Integer. Maximum size for the generator queue.\n If unspecified, `max_queue_size` will default to 10.\n workers: Integer. Maximum number of processes to spin up\n when using process-based threading.\n If unspecified, `workers` will default to 1. If 0, will\n execute the generator on the main thread.\n use_multiprocessing: Boolean.\n If `True`, use process-based threading.\n If unspecified, `use_multiprocessing` will default to `False`.\n Note that because this implementation relies on multiprocessing,\n you should not pass non-picklable arguments to the generator\n as they can't be passed easily to children processes.\n shuffle: Boolean. Whether to shuffle the order of the batches at\n the beginning of each epoch. Only used with instances\n of `Sequence` (`keras.utils.Sequence`).\n Has no effect when `steps_per_epoch` is not `None`.\n initial_epoch: Epoch at which to start training\n (useful for resuming a previous training run)\n\n Returns:\n A `History` object.\n\n Example:\n\n ```python\n def generate_arrays_from_file(path):\n while 1:\n f = open(path)\n for line in f:\n # create numpy arrays of input data\n # and labels, from each line in the file\n x1, x2, y = process_line(line)\n yield ({'input_1': x1, 'input_2': x2}, {'output': y})\n f.close()\n\n model.fit_generator(generate_arrays_from_file('/my_file.txt'),\n steps_per_epoch=10000, epochs=10)\n ```\n Raises:\n ValueError: In case the generator yields data in an invalid format.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`fit_generator` is not supported for '\n 'models compiled with DistributionStrategy.')\n\n if not self.built and not self._is_graph_network:\n raise NotImplementedError(\n '`fit_generator` is not yet enabled for unbuilt Model subclasses')\n\n return training_generator.fit_generator(\n self,\n generator,\n steps_per_epoch=steps_per_epoch,\n epochs=epochs,\n verbose=verbose,\n callbacks=callbacks,\n validation_data=validation_data,\n validation_steps=validation_steps,\n class_weight=class_weight,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n shuffle=shuffle,\n initial_epoch=initial_epoch)\n\n def evaluate_generator(self,\n generator,\n steps=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n verbose=0):\n \"\"\"Evaluates the model on a data generator.\n\n The generator should return the same kind of data\n as accepted by `test_on_batch`.\n\n Arguments:\n generator: Generator yielding tuples (inputs, targets)\n or (inputs, targets, sample_weights)\n or an instance of Sequence (keras.utils.Sequence)\n object in order to avoid duplicate data\n when using multiprocessing.\n steps: Total number of steps (batches of samples)\n to yield from `generator` before stopping.\n Optional for `Sequence`: if unspecified, will use\n the `len(generator)` as a number of steps.\n max_queue_size: maximum size for the generator queue\n workers: Integer. Maximum number of processes to spin up\n when using process-based threading.\n If unspecified, `workers` will default to 1. If 0, will\n execute the generator on the main thread.\n use_multiprocessing: Boolean.\n If `True`, use process-based threading.\n If unspecified, `use_multiprocessing` will default to `False`.\n Note that because this implementation relies on multiprocessing,\n you should not pass non-picklable arguments to the generator\n as they can't be passed easily to children processes.\n verbose: Verbosity mode, 0 or 1.\n\n Returns:\n Scalar test loss (if the model has a single output and no metrics)\n or list of scalars (if the model has multiple outputs\n and/or metrics). The attribute `model.metrics_names` will give you\n the display labels for the scalar outputs.\n\n Raises:\n ValueError: in case of invalid arguments.\n\n Raises:\n ValueError: In case the generator yields data in an invalid format.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`evaluate_generator` is not supported for '\n 'models compiled with DistributionStrategy.')\n\n if not self.built and not self._is_graph_network:\n raise NotImplementedError(\n '`evaluate_generator` is not yet enabled for '\n 'unbuilt Model subclasses')\n\n return training_generator.evaluate_generator(\n self,\n generator,\n steps=steps,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n verbose=verbose)\n\n def predict_generator(self,\n generator,\n steps=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n verbose=0):\n \"\"\"Generates predictions for the input samples from a data generator.\n\n The generator should return the same kind of data as accepted by\n `predict_on_batch`.\n\n Arguments:\n generator: Generator yielding batches of input samples\n or an instance of Sequence (keras.utils.Sequence)\n object in order to avoid duplicate data\n when using multiprocessing.\n steps: Total number of steps (batches of samples)\n to yield from `generator` before stopping.\n Optional for `Sequence`: if unspecified, will use\n the `len(generator)` as a number of steps.\n max_queue_size: Maximum size for the generator queue.\n workers: Integer. Maximum number of processes to spin up\n when using process-based threading.\n If unspecified, `workers` will default to 1. If 0, will\n execute the generator on the main thread.\n use_multiprocessing: Boolean.\n If `True`, use process-based threading.\n If unspecified, `use_multiprocessing` will default to `False`.\n Note that because this implementation relies on multiprocessing,\n you should not pass non-picklable arguments to the generator\n as they can't be passed easily to children processes.\n verbose: verbosity mode, 0 or 1.\n\n Returns:\n Numpy array(s) of predictions.\n\n Raises:\n ValueError: In case the generator yields data in an invalid format.\n \"\"\"\n if self._distribution_strategy:\n raise NotImplementedError('`predict_generator` is not supported for '\n 'models compiled with DistributionStrategy.')\n\n if not self.built and not self._is_graph_network:\n raise NotImplementedError(\n '`predict_generator` is not yet enabled for unbuilt Model subclasses')\n\n return training_generator.predict_generator(\n self,\n generator,\n steps=steps,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n verbose=verbose)\n\n def _get_callback_model(self):\n \"\"\"Returns the Callback Model for this Model.\"\"\"\n\n if hasattr(self, '_replicated_model') and self._replicated_model:\n # When using training_distributed, we set the callback model\n # to an instance of the `DistributedModel` that we create in\n # the `compile` call. The `DistributedModel` is initialized\n # with the first replicated model. We need to set the callback\n # model to a DistributedModel to allow us to override saving\n # and loading weights when we checkpoint the model during training.\n return self._replicated_model\n if hasattr(self, 'callback_model') and self.callback_model:\n return self.callback_model\n return self\n\n\nclass DistributedCallbackModel(Model):\n \"\"\"Model that is used for callbacks with DistributionStrategy.\"\"\"\n\n def __init__(self, model):\n super(DistributedCallbackModel, self).__init__()\n # TODO(anjalisridhar): Right now the only attributes set are the layer and\n # weights. We may need to set additional attributes as needed since we have\n # not called compile on this model.\n\n def set_original_model(self, orig_model):\n self._original_model = orig_model\n\n def save_weights(self, filepath, overwrite=True, save_format=None):\n self._replicated_model.save_weights(filepath, overwrite=overwrite,\n save_format=save_format)\n\n def save(self, filepath, overwrite=True, include_optimizer=True):\n # save weights from the distributed model to the original model\n distributed_model_weights = self.get_weights()\n self._original_model.set_weights(distributed_model_weights)\n # TODO(anjalisridhar): Do we need to save the original model here?\n # Saving the first replicated model works as well.\n self._original_model.save(filepath, overwrite=True, include_optimizer=False)\n\n def load_weights(self, filepath, by_name=False):\n self._original_model.load_weights(filepath, by_name=False)\n # Copy the weights from the original model to each of the replicated models.\n orig_model_weights = self._original_model.get_weights()\n distributed_training_utils.set_weights(\n self._original_model._distribution_strategy, self, # pylint: disable=protected-access\n orig_model_weights)\n\n def __getattr__(self, item):\n # Whitelisted atttributes of the model that can be accessed by the user\n # during a callback.\n if item not in ['_setattr_tracking']:\n logging.warning('You are accessing attribute ' + item + 'of the'\n 'DistributedCallbackModel that may not have been set'\n 'correctly.')\n", "# Copyright 2016 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\"\"\"Tests for Inception V3 application.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.keras.applications.imagenet_utils import preprocess_input\nfrom tensorflow.python.platform import test\n\n\nclass ImageNetUtilsTest(test.TestCase):\n\n def test_preprocess_input(self):\n # Test batch of images\n x = np.random.uniform(0, 255, (2, 10, 10, 3))\n self.assertEqual(preprocess_input(x).shape, x.shape)\n out1 = preprocess_input(x, 'channels_last')\n out2 = preprocess_input(np.transpose(x, (0, 3, 1, 2)), 'channels_first')\n self.assertAllClose(out1, out2.transpose(0, 2, 3, 1))\n\n # Test single image\n x = np.random.uniform(0, 255, (10, 10, 3))\n self.assertEqual(preprocess_input(x).shape, x.shape)\n out1 = preprocess_input(x, 'channels_last')\n out2 = preprocess_input(np.transpose(x, (2, 0, 1)), 'channels_first')\n self.assertAllClose(out1, out2.transpose(1, 2, 0))\n\n def test_preprocess_input_symbolic(self):\n # Test image batch\n x = np.random.uniform(0, 255, (2, 10, 10, 3))\n inputs = keras.layers.Input(shape=x.shape[1:])\n outputs = keras.layers.Lambda(\n preprocess_input, output_shape=x.shape[1:])(inputs)\n model = keras.models.Model(inputs, outputs)\n assert model.predict(x).shape == x.shape\n # pylint: disable=g-long-lambda\n outputs1 = keras.layers.Lambda(lambda x:\n preprocess_input(x, 'channels_last'),\n output_shape=x.shape[1:])(inputs)\n model1 = keras.models.Model(inputs, outputs1)\n out1 = model1.predict(x)\n x2 = np.transpose(x, (0, 3, 1, 2))\n inputs2 = keras.layers.Input(shape=x2.shape[1:])\n # pylint: disable=g-long-lambda\n outputs2 = keras.layers.Lambda(lambda x:\n preprocess_input(x, 'channels_first'),\n output_shape=x2.shape[1:])(inputs2)\n model2 = keras.models.Model(inputs2, outputs2)\n out2 = model2.predict(x2)\n self.assertAllClose(out1, out2.transpose(0, 2, 3, 1))\n\n # Test single image\n x = np.random.uniform(0, 255, (10, 10, 3))\n inputs = keras.layers.Input(shape=x.shape)\n outputs = keras.layers.Lambda(preprocess_input,\n output_shape=x.shape)(inputs)\n model = keras.models.Model(inputs, outputs)\n assert model.predict(x[np.newaxis])[0].shape == x.shape\n # pylint: disable=g-long-lambda\n outputs1 = keras.layers.Lambda(lambda x:\n preprocess_input(x, 'channels_last'),\n output_shape=x.shape)(inputs)\n model1 = keras.models.Model(inputs, outputs1)\n out1 = model1.predict(x[np.newaxis])[0]\n x2 = np.transpose(x, (2, 0, 1))\n inputs2 = keras.layers.Input(shape=x2.shape)\n outputs2 = keras.layers.Lambda(lambda x:\n preprocess_input(x, 'channels_first'),\n output_shape=x2.shape)(inputs2) # pylint: disable=g-long-lambda\n model2 = keras.models.Model(inputs2, outputs2)\n out2 = model2.predict(x2[np.newaxis])[0]\n self.assertAllClose(out1, out2.transpose(1, 2, 0))\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2018 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\"\"\"Test cases for eager execution using XLA.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.compiler.tests import xla_test\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.layers import convolutional\nfrom tensorflow.python.layers import pooling\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import gen_random_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.training import adam\n\n\nclass EagerTest(xla_test.XLATestCase):\n\n def testBasic(self):\n with self.test_scope():\n three = constant_op.constant(3)\n five = constant_op.constant(5)\n product = three * five\n self.assertAllEqual(15, product)\n\n def testGradientTape(self):\n with self.test_scope():\n\n x = constant_op.constant(1.0)\n y = constant_op.constant(10.0)\n with backprop.GradientTape(persistent=True) as tape:\n tape.watch(x)\n tape.watch(y)\n a = x + y + x * y\n da_dx = tape.gradient(a, x)\n da_dy = tape.gradient(a, y)\n\n self.assertEqual(11.0, da_dx.numpy())\n self.assertEqual(2.0, da_dy.numpy())\n\n def testExecuteListOutputLen0(self):\n with self.test_scope():\n empty = constant_op.constant([], dtype=dtypes.float32)\n result = array_ops.unstack(empty, 0)\n self.assertTrue(isinstance(result, list))\n self.assertEqual(0, len(result))\n\n def testExecuteListOutputLen1(self):\n with self.test_scope():\n split_dim = constant_op.constant(1)\n value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]])\n result = array_ops.split(value, 1, axis=split_dim)\n self.assertTrue(isinstance(result, list))\n self.assertEqual(1, len(result))\n self.assertAllEqual([[0, 1, 2], [3, 4, 5]], result[0])\n\n def testExecuteListOutputLen3(self):\n with self.test_scope():\n split_dim = constant_op.constant(1)\n value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]])\n result = array_ops.split(value, 3, axis=split_dim)\n self.assertTrue(isinstance(result, list))\n self.assertEqual(3, len(result))\n self.assertAllEqual([[0], [3]], result[0])\n self.assertAllEqual([[1], [4]], result[1])\n self.assertAllEqual([[2], [5]], result[2])\n\n def testBasicGraph(self):\n # Run some ops eagerly\n with self.test_scope():\n three = constant_op.constant(3)\n five = constant_op.constant(5)\n product = three * five\n self.assertAllEqual(15, product)\n\n # Run some ops graphly\n with context.graph_mode(), self.test_session() as sess:\n with self.test_scope():\n three = constant_op.constant(3)\n five = constant_op.constant(5)\n product = three * five\n self.assertAllEqual(15, sess.run(product))\n\n def testDegenerateSlices(self):\n with self.test_scope():\n npt = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3)\n t = constant_op.constant(npt)\n # degenerate by offering a forward interval with a negative stride\n self.assertAllEqual(npt[0:-1:-1, :, :], t[0:-1:-1, :, :])\n # degenerate with a reverse interval with a positive stride\n self.assertAllEqual(npt[-1:0, :, :], t[-1:0, :, :])\n # empty interval in every dimension\n self.assertAllEqual(npt[-1:0, 2:2, 2:3:-1], t[-1:0, 2:2, 2:3:-1])\n\n def testIdentity(self):\n with self.test_scope():\n self.assertAllEqual(2, array_ops.identity(2))\n\n def testRandomOps(self):\n with self.test_scope():\n tensor = gen_random_ops.random_uniform((2, 2), dtypes.float32)\n row0 = tensor[0].numpy()\n row1 = tensor[1].numpy()\n # It should be very unlikely to rng to generate two equal rows.\n self.assertFalse((row0 == row1).all())\n\n def testIdentityOnVariable(self):\n with self.test_scope():\n v = resource_variable_ops.ResourceVariable(True)\n i = array_ops.identity(v)\n self.assertAllEqual(True, i.numpy())\n\n def testAssignAddVariable(self):\n with self.test_scope():\n v = resource_variable_ops.ResourceVariable(1.0)\n v.assign_add(2.0)\n self.assertEqual(3.0, v.numpy())\n\n def testReadAssignRead(self):\n with self.test_scope():\n v = resource_variable_ops.ResourceVariable(1.0)\n val1 = v.read_value()\n v.assign_add(2.0)\n val2 = v.read_value()\n self.assertEqual(1.0, val1.numpy())\n self.assertEqual(3.0, val2.numpy())\n\n def testGradient(self):\n def f(x):\n return x\n\n with self.test_scope():\n grad_fn = backprop.gradients_function(f)\n self.assertAllEqual(2., grad_fn(1., dy=2.)[0])\n\n def testVariableGradient(self):\n with self.test_scope():\n v0 = resource_variable_ops.ResourceVariable(1.0)\n\n def f():\n x = v0 * v0\n return x\n\n grads = backprop.implicit_grad(f)()\n self.assertEqual(2., grads[0][0].numpy())\n\n def testMultipleVariableReads(self):\n # This test makes sure consecutive variable reads don't copy\n # the underlying memory.\n with self.test_scope():\n # Create 128MiB variables\n var = resource_variable_ops.ResourceVariable(\n array_ops.ones([32, 1024, 1024]))\n\n # Read the same variable 100 times. If the underlying tensor\n # is not copied, this is a trivial operation. If it is copied,\n # this will eat over 13GB and OOM.\n values = []\n for _ in range(100):\n values.append(var.value())\n\n # The shape, shape_n, size, and rank are tested here because their\n # execution kernels (as opposed to compilation only tf2xla kernels)\n # are distincts from tf2xla kernels.\n\n def testShape(self):\n def const(value):\n return array_ops.shape(\n constant_op.constant(value)).numpy()\n\n def ones(value):\n return array_ops.shape(\n array_ops.ones(value)).numpy()\n\n with self.test_scope():\n # Shapes of directly constructed tensors\n self.assertAllEqual([], const(3))\n self.assertAllEqual([3], const([1.0, 2.0, 3.0]))\n self.assertAllEqual([2, 2], const([[1.0, 2.0], [3.0, 4.0]]))\n self.assertAllEqual([2, 1, 2], const([[[1.0, 2.0]], [[3.0, 4.0]]]))\n\n # Shapes of tensors created by op running on device\n # We make this distinction because directly constructed tensors\n # are treated differently in a few places that can influence shape:\n # - they always have on_host_tensor\n # - they and their shapes can be cached\n # - they end up on device via a copy, instead of as program output\n self.assertAllEqual([], ones([]))\n self.assertAllEqual([3], ones([3]))\n self.assertAllEqual([2, 2], ones([2, 2]))\n self.assertAllEqual([2, 1, 2], ones([2, 1, 2]))\n\n def testShapeN(self):\n with self.test_scope():\n # Shapes of directly constructed tensors\n shapes = array_ops.shape_n([\n constant_op.constant(1.0),\n constant_op.constant([1.0, 2.0, 3.0]),\n constant_op.constant([[1.0, 2.0], [3.0, 4.0]])])\n self.assertAllEqual(\n [[], [3], [2, 2]],\n [x.numpy().tolist() for x in shapes])\n\n # Shapes of tensors created by op running on device\n shapes = array_ops.shape_n([\n array_ops.ones([]),\n array_ops.ones([3]),\n array_ops.ones([2, 2])])\n self.assertAllEqual(\n [[], [3], [2, 2]],\n [x.numpy().tolist() for x in shapes])\n\n def testSize(self):\n with self.test_scope():\n self.assertEqual(\n 1, array_ops.size(constant_op.constant(1.0)).numpy())\n self.assertEqual(\n 3, array_ops.size(constant_op.constant([1.0, 2.0, 3.0])).numpy())\n self.assertEqual(\n 4, array_ops.size(\n constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy())\n\n def testRank(self):\n with self.test_scope():\n self.assertEqual(\n 0, array_ops.rank(constant_op.constant(1.0)).numpy())\n self.assertEqual(\n 1, array_ops.rank(constant_op.constant([1.0, 2.0, 3.0])).numpy())\n self.assertEqual(\n 2, array_ops.rank(\n constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy())\n\n def testAdam(self):\n with self.test_scope():\n optimizer = adam.AdamOptimizer(0.1)\n x = resource_variable_ops.ResourceVariable(10.0)\n with backprop.GradientTape() as tape:\n y = x * x\n dy_dx = tape.gradient(y, x)\n optimizer.apply_gradients([(dy_dx, x)])\n self.assertAlmostEqual(9.9, x.numpy(), places=3)\n\n def testAdamSparse(self):\n with ops.device('/cpu:0'):\n # Create 2-D embedding for 3 objects on CPU because sparse/sliced updates\n # are not implemented on TPU.\n embedding_matrix = resource_variable_ops.ResourceVariable(\n array_ops.ones([3, 2]))\n\n with self.test_scope():\n with backprop.GradientTape() as tape:\n embedding = embedding_ops.embedding_lookup(embedding_matrix, [1])\n y = math_ops.reduce_sum(embedding)\n dy_dx = tape.gradient(y, embedding_matrix)\n self.assertIsInstance(dy_dx, ops.IndexedSlices)\n optimizer = adam.AdamOptimizer(0.1)\n # The gradient application operations will run on CPU because optimizer\n # updates are always collocated with the variable.\n optimizer.apply_gradients([(dy_dx, embedding_matrix)])\n\n # This assign_add will run on CPU because when an input to an\n # operation is a resource, this operation is placed on the resource's\n # device by the eager runtime.\n embedding_matrix.assign_add(array_ops.ones([3, 2]))\n\n self.assertAllClose([[2.0, 2.0],\n [1.9, 1.9],\n [2.0, 2.0]], embedding_matrix.numpy())\n\n\nclass EagerFunctionTest(xla_test.XLATestCase):\n\n def testBasic(self):\n with self.test_scope():\n matmul = function.defun(math_ops.matmul)\n t = constant_op.constant([[1.0, 2.0], [3.0, 4.0]])\n sq = matmul(t, t, transpose_a=True)\n self.assertAllEqual(sq.numpy().reshape(-1), [10, 14, 14, 20])\n\n def testConv(self):\n if 'GPU' in self.device:\n # TODO(b/32333178)\n self.skipTest('Current implementation of RandomStandardNormal kernel '\n 'is very slow on GPU, and has been blacklisted.')\n with self.test_scope():\n data_format = 'channels_last'\n conv = convolutional.Conv2D(\n filters=1, kernel_size=2, padding='VALID',\n data_format=data_format, activation=nn_ops.relu,\n kernel_initializer=init_ops.ones_initializer(),\n bias_initializer=init_ops.zeros_initializer())\n pool = pooling.MaxPooling2D(2, 2, data_format=data_format)\n\n def model(x):\n x = conv(x)\n return pool(x)\n model = function.defun(model)\n\n x = array_ops.ones([1, 4, 4, 1])\n y = model(x)\n self.assertAllEqual(y.numpy(), [[[[4.]]]])\n\n def testReadVariable(self):\n with self.test_scope():\n v = resource_variable_ops.ResourceVariable(1.0)\n\n @function.defun\n def f():\n return v.read_value()\n\n var = f()\n self.assertEqual(1.0, var.numpy())\n\n def testUpdateVariable(self):\n with self.test_scope():\n v = resource_variable_ops.ResourceVariable(1.0)\n\n def f(v):\n v.assign_add(1.0)\n return v\n\n f = function.defun(f)\n\n var = f(v)\n self.assertEqual(2.0, var.numpy())\n\n def testAllArgumentKinds(self):\n \"\"\"Test a complex function that takes different argument kinds.\n\n tf2xla machinery that translates, compiles, and runs defuns\n classifies arguments into: compile-time constants, regular tensors,\n and resources. This test creates a function with a mix of all these\n kinds. Moreover, the order of function arguments is intentionally mixed up.\n\n This also tests the case when the same argument is a compile-time constant\n as well as used in an operation that normally expects its inputs to be\n in device memory - addition in this case.\n \"\"\"\n with self.test_scope():\n def foo(c1, r1, v1, c2, v2, r2):\n # c1 and c2 are compile-time constants\n # r1 and r2 are regular tensors\n # v1 and v2 are resource variables\n a = c1 + r1\n b = math_ops.cast(c2, dtypes.float32) + v2\n c = array_ops.slice(v1, c1, c2)\n d = r2 * v2\n return a, b, c, d\n\n foo = function.defun(foo)\n\n c1 = [0, 0]\n c2 = array_ops.ones([2], dtype=dtypes.int32)\n\n r1 = array_ops.ones([2])\n r2 = [[2., 2.], [3., 3.]]\n\n v1 = resource_variable_ops.ResourceVariable([[1., 2.], [3., 4.]])\n v2 = resource_variable_ops.ResourceVariable([[10., 20.], [30., 40.]])\n\n a, b, c, d = foo(c1, r1, v1, c2, v2, r2)\n\n self.assertAllEqual([1, 1], a.numpy())\n self.assertAllEqual([[11., 21.], [31., 41.]], b.numpy())\n self.assertAllEqual([[1.]], c.numpy())\n self.assertAllEqual([[20., 40.], [90., 120.]], d.numpy())\n\n def testDefunInGradientTape(self):\n with self.test_scope():\n v0 = resource_variable_ops.ResourceVariable(5.0)\n\n @function.defun\n def f(x):\n x = v0 * v0 * x\n return x\n\n x = constant_op.constant(3.0)\n with backprop.GradientTape() as tape:\n y = f(x)\n dy = tape.gradient(y, v0)\n\n self.assertEqual(75, y.numpy())\n self.assertEqual(30, dy.numpy())\n\n def testGradientTapeInDefun(self):\n with self.test_scope():\n v0 = resource_variable_ops.ResourceVariable(5.0)\n\n @function.defun\n def f():\n x = constant_op.constant(1.0)\n with backprop.GradientTape() as tape:\n y = v0 * x\n dy = tape.gradient(y, v0)\n return dy\n\n dy = f()\n self.assertEqual(1.0, dy.numpy())\n\n def testSliceInDefun(self):\n with self.test_scope():\n\n @function.defun\n def f(x, y):\n return x[0::2, y:, ...]\n\n x = array_ops.ones([2, 3, 4])\n y = array_ops.ones([], dtype=dtypes.int32)\n with backprop.GradientTape() as tape:\n tape.watch(x)\n tape.watch(y)\n z = f(x, y)\n dz = tape.gradient(z, x)\n\n self.assertAllEqual(np.ones([1, 2, 4]), z.numpy())\n self.assertAllEqual((2, 3, 4), dz.shape.as_list())\n\n def testNestedDefun(self):\n self.skipTest('Nested defuns do not work on TPU at the moment')\n with self.test_scope():\n\n @function.defun\n def times_two(x):\n return 2 * x\n\n @function.defun\n def two_x_plus_1(x):\n return times_two(x) + 1\n\n x = constant_op.constant([2, 3, 4])\n y = two_x_plus_1(x)\n self.assertAllEqual([5, 7, 9], y.numpy())\n\n\nclass ExcessivePaddingTest(xla_test.XLATestCase):\n \"\"\"Test that eager execution works with TPU flattened tensors.\n\n Tensors that would normally be excessively padded when written\n to TPU memory are reshaped to 1-D flat tensors.\n\n This test case verifies that such tensors work with eager execution.\n\n The flattening currently only happens on TPU, but tests should work\n fine with all backends as flattening is transparent.\n \"\"\"\n\n def testFromConstant(self):\n with self.test_scope():\n # Create constant of shape [100, 2, 1]. This tensor would be\n # excessively padded on TPU.\n tensor = constant_op.constant(100 * [[[10.0], [2.0]]])\n # Use reduce_sum since it requires correctly working with\n # a particular dimension.\n reduced = math_ops.reduce_sum(tensor, axis=1)\n self.assertAllEqual(100 * [[12.0]], reduced)\n\n def testFromOperation(self):\n with self.test_scope():\n tensor = array_ops.ones([3, 100, 2, 2])\n reduced = math_ops.reduce_sum(tensor, axis=[0, 2, 3])\n self.assertAllEqual(100 * [12.0], reduced)\n\n def testAsFunctionInput(self):\n with self.test_scope():\n\n @function.defun\n def f(x):\n return math_ops.reduce_sum(x, axis=2)\n\n tensor = constant_op.constant(100 * [[[10.0, 2.0]]])\n reduced = f(tensor)\n self.assertAllEqual(100 * [[12.0]], reduced)\n\n def testAsFunctionOutput(self):\n with self.test_scope():\n\n @function.defun\n def f(x):\n return x * constant_op.constant(100 * [[[10.0, 2.0]]])\n\n y = f(3)\n reduced = math_ops.reduce_sum(y, axis=2)\n self.assertAllEqual(100 * [[36.0]], reduced)\n\n\ndef multiple_tpus():\n devices = context.context().devices()\n return len([d for d in devices if 'device:TPU:' in d]) > 1\n\n\nclass MultiDeviceTest(xla_test.XLATestCase):\n \"\"\"Test running TPU computation on more than one core.\"\"\"\n\n def testBasic(self):\n if not multiple_tpus():\n self.skipTest('MultiDeviceTest requires multiple TPU devices.')\n\n # Compute 10 on TPU core 0\n with ops.device('device:TPU:0'):\n two = constant_op.constant(2)\n five = constant_op.constant(5)\n ten = two * five\n self.assertAllEqual(10, ten)\n\n # Compute 6 on TPU core 1\n with ops.device('device:TPU:1'):\n two = constant_op.constant(2)\n three = constant_op.constant(3)\n six = two * three\n self.assertAllEqual(6, six)\n\n # Copy 10 and 6 to CPU and sum them\n self.assertAllEqual(16, ten + six)\n\n\nif __name__ == '__main__':\n ops.enable_eager_execution(\n config=config_pb2.ConfigProto(log_device_placement=True))\n googletest.main()\n", "# Copyright 2018 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\"\"\"Defines `{Additive,Multiplicative}SwapRegretOptimizer`s.\n\nThese optimizers minimize a `ConstrainedMinimizationProblem` by using a\nswap-regret minimizing algorithm (either SGD or multiplicative weights) to learn\nwhat weights should be associated with the objective function and constraints.\nThese algorithms do *not* use Lagrange multipliers, but the idea is similar.\nThe main differences between the formulation used here, and the standard\nLagrangian formulation, are that (i) the objective function is weighted, in\naddition to the constraints, and (ii) we learn a matrix of weights, instead of a\nvector.\n\nFor the purposes of constrained optimization, at least in theory,\nexternal-regret minimization suffices if the `ConstrainedMinimizationProblem`\nwe're optimizing doesn't have any `proxy_constraints`, while swap-regret\nminimization should be used if `proxy_constraints` are present.\n\nFor more specifics, please refer to:\n\n> Cotter, Jiang and Sridharan. \"Two-Player Games for Efficient Non-Convex\n> Constrained Optimization\".\n> [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500)\n\nThe formulation used by both of the SwapRegretOptimizers can be found in\nDefinition 2, and is discussed in Section 4. The\n`MultiplicativeSwapRegretOptimizer` is most similar to Algorithm 2 in Section 4,\nwith the difference being that it uses `tf.train.Optimizer`s, instead of SGD,\nfor the \"inner\" updates. The `AdditiveSwapRegretOptimizer` differs further in\nthat it performs additive (instead of multiplicative) updates of the stochastic\nmatrix.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport math\n\nimport six\n\nfrom tensorflow.contrib.constrained_optimization.python import constrained_optimizer\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import standard_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.training import optimizer as train_optimizer\n\n\ndef _maximal_eigenvector_power_method(matrix,\n epsilon=1e-6,\n maximum_iterations=100):\n \"\"\"Returns the maximal right-eigenvector of `matrix` using the power method.\n\n Args:\n matrix: 2D Tensor, the matrix of which we will find the maximal\n right-eigenvector.\n epsilon: nonnegative float, if two iterations of the power method differ (in\n L2 norm) by no more than epsilon, we will terminate.\n maximum_iterations: nonnegative int, if we perform this many iterations, we\n will terminate.\n\n Result:\n The maximal right-eigenvector of `matrix`.\n\n Raises:\n ValueError: If the epsilon or maximum_iterations parameters violate their\n bounds.\n \"\"\"\n if epsilon <= 0.0:\n raise ValueError(\"epsilon must be strictly positive\")\n if maximum_iterations <= 0:\n raise ValueError(\"maximum_iterations must be strictly positive\")\n\n def while_loop_condition(iteration, eigenvector, old_eigenvector):\n \"\"\"Returns false if the while loop should terminate.\"\"\"\n not_done = (iteration < maximum_iterations)\n not_converged = (standard_ops.norm(eigenvector - old_eigenvector) > epsilon)\n return standard_ops.logical_and(not_done, not_converged)\n\n def while_loop_body(iteration, eigenvector, old_eigenvector):\n \"\"\"Performs one iteration of the power method.\"\"\"\n del old_eigenvector # Needed by the condition, but not the body.\n iteration += 1\n # We need to use tf.matmul() and tf.expand_dims(), instead of\n # tf.tensordot(), since the former will infer the shape of the result, while\n # the latter will not (tf.while_loop() needs the shapes).\n new_eigenvector = standard_ops.matmul(\n matrix, standard_ops.expand_dims(eigenvector, 1))[:, 0]\n new_eigenvector /= standard_ops.norm(new_eigenvector)\n return (iteration, new_eigenvector, eigenvector)\n\n iteration = standard_ops.constant(0)\n eigenvector = standard_ops.ones_like(matrix[:, 0])\n eigenvector /= standard_ops.norm(eigenvector)\n\n # We actually want a do-while loop, so we explicitly call while_loop_body()\n # once before tf.while_loop().\n iteration, eigenvector, old_eigenvector = while_loop_body(\n iteration, eigenvector, eigenvector)\n iteration, eigenvector, old_eigenvector = control_flow_ops.while_loop(\n while_loop_condition,\n while_loop_body,\n loop_vars=(iteration, eigenvector, old_eigenvector),\n name=\"power_method\")\n\n return eigenvector\n\n\ndef _project_stochastic_matrix_wrt_euclidean_norm(matrix):\n \"\"\"Projects its argument onto the set of left-stochastic matrices.\n\n This algorithm is O(n^3) at worst, where `matrix` is n*n. It can be done in\n O(n^2 * log(n)) time by sorting each column (and maybe better with a different\n algorithm), but the algorithm implemented here is easier to implement in\n TensorFlow.\n\n Args:\n matrix: 2d square tensor, the matrix to project.\n\n Returns:\n The 2d square tensor that results from projecting `matrix` onto the set of\n left-stochastic matrices w.r.t. the Euclidean norm applied column-wise\n (i.e. the Frobenius norm).\n\n Raises:\n ValueError: if the `matrix` tensor does not have a fully-known shape, or is\n not two-dimensional and square.\n \"\"\"\n matrix_shape = matrix.get_shape()\n if matrix_shape is None:\n raise ValueError(\"matrix must have known shape\")\n if matrix_shape.ndims != 2:\n raise ValueError(\n \"matrix must be two dimensional (instead is %d-dimensional)\" %\n matrix_shape.ndims)\n if matrix_shape[0] != matrix_shape[1]:\n raise ValueError(\"matrix must be square (instead has shape (%d,%d))\" %\n (matrix_shape[0], matrix_shape[1]))\n dimension = matrix_shape[0].value\n if dimension is None:\n raise ValueError(\"matrix must have fully-known shape\")\n\n def while_loop_condition(iteration, matrix, inactive, old_inactive):\n \"\"\"Returns false if the while loop should terminate.\"\"\"\n del matrix # Needed by the body, but not the condition.\n not_done = (iteration < dimension)\n not_converged = standard_ops.reduce_any(\n standard_ops.not_equal(inactive, old_inactive))\n return standard_ops.logical_and(not_done, not_converged)\n\n def while_loop_body(iteration, matrix, inactive, old_inactive):\n \"\"\"Performs one iteration of the projection.\"\"\"\n del old_inactive # Needed by the condition, but not the body.\n iteration += 1\n scale = (1.0 - standard_ops.reduce_sum(\n matrix, axis=0, keepdims=True)) / standard_ops.maximum(\n 1.0, standard_ops.reduce_sum(inactive, axis=0, keepdims=True))\n matrix += scale * inactive\n new_inactive = standard_ops.to_float(matrix > 0)\n matrix *= new_inactive\n return (iteration, matrix, new_inactive, inactive)\n\n iteration = standard_ops.constant(0)\n inactive = standard_ops.ones_like(matrix)\n\n # We actually want a do-while loop, so we explicitly call while_loop_body()\n # once before tf.while_loop().\n iteration, matrix, inactive, old_inactive = while_loop_body(\n iteration, matrix, inactive, inactive)\n iteration, matrix, inactive, old_inactive = control_flow_ops.while_loop(\n while_loop_condition,\n while_loop_body,\n loop_vars=(iteration, matrix, inactive, old_inactive),\n name=\"euclidean_projection\")\n\n return matrix\n\n\ndef _project_log_stochastic_matrix_wrt_kl_divergence(log_matrix):\n \"\"\"Projects its argument onto the set of log-left-stochastic matrices.\n\n Args:\n log_matrix: 2d square tensor, the element-wise logarithm of the matrix to\n project.\n\n Returns:\n The 2d square tensor that results from projecting exp(`matrix`) onto the set\n of left-stochastic matrices w.r.t. the KL-divergence applied column-wise.\n \"\"\"\n\n # For numerical reasons, make sure that the largest matrix element is zero\n # before exponentiating.\n log_matrix -= standard_ops.reduce_max(log_matrix, axis=0, keepdims=True)\n log_matrix -= standard_ops.log(\n standard_ops.reduce_sum(\n standard_ops.exp(log_matrix), axis=0, keepdims=True))\n return log_matrix\n\n\[email protected]_metaclass(abc.ABCMeta)\nclass _SwapRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):\n \"\"\"Base class representing a `_SwapRegretOptimizer`.\n\n This class contains most of the logic for performing constrained optimization,\n minimizing external regret for the constraints player. What it *doesn't* do is\n keep track of the internal state (the stochastic matrix). Instead, the state\n is accessed via the _initial_state(), _stochastic_matrix(),\n _constraint_grad_and_var() and _projection_op() methods.\n\n The reason for this is that we want to make it easy to implement different\n representations of the internal state. For example, for additive updates, it's\n most natural to store the stochastic matrix directly, whereas for\n multiplicative updates, it's most natural to store its element-wise logarithm.\n\n For more specifics, please refer to:\n\n > Cotter, Jiang and Sridharan. \"Two-Player Games for Efficient Non-Convex\n > Constrained Optimization\".\n > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500)\n\n The formulation used by `_SwapRegretOptimizer`s can be found in Definition 2,\n and is discussed in Section 4. Such optimizers are most similar to Algorithm\n 2 in Section 4. Most notably, the internal state is a left-stochastic matrix\n of shape (m+1,m+1), where m is the number of constraints.\n \"\"\"\n\n def __init__(self, optimizer, constraint_optimizer=None):\n \"\"\"Constructs a new `_SwapRegretOptimizer`.\n\n The difference between `optimizer` and `constraint_optimizer` (if the latter\n is provided) is that the former is used for learning the model parameters,\n while the latter us used for the update to the constraint/objective weight\n matrix (the analogue of Lagrange multipliers). If no `constraint_optimizer`\n is provided, then `optimizer` is used for both.\n\n Args:\n optimizer: tf.train.Optimizer, used to optimize the objective and\n proxy_constraints portion of ConstrainedMinimizationProblem. If\n constraint_optimizer is not provided, this will also be used to optimize\n the Lagrange multiplier analogues.\n constraint_optimizer: optional tf.train.Optimizer, used to optimize the\n Lagrange multiplier analogues.\n\n Returns:\n A new `_SwapRegretOptimizer`.\n \"\"\"\n super(_SwapRegretOptimizer, self).__init__(optimizer=optimizer)\n self._constraint_optimizer = constraint_optimizer\n\n @property\n def constraint_optimizer(self):\n \"\"\"Returns the `tf.train.Optimizer` used for the matrix.\"\"\"\n return self._constraint_optimizer\n\n @abc.abstractmethod\n def _initial_state(self, num_constraints):\n pass\n\n @abc.abstractmethod\n def _stochastic_matrix(self, state):\n pass\n\n def _distribution(self, state):\n distribution = _maximal_eigenvector_power_method(\n self._stochastic_matrix(state))\n distribution = standard_ops.abs(distribution)\n distribution /= standard_ops.reduce_sum(distribution)\n return distribution\n\n @abc.abstractmethod\n def _constraint_grad_and_var(self, state, gradient):\n pass\n\n @abc.abstractmethod\n def _projection_op(self, state, name=None):\n pass\n\n def minimize_constrained(self,\n minimization_problem,\n global_step=None,\n var_list=None,\n gate_gradients=train_optimizer.Optimizer.GATE_OP,\n aggregation_method=None,\n colocate_gradients_with_ops=False,\n name=None,\n grad_loss=None):\n \"\"\"Returns an `Op` for minimizing the constrained problem.\n\n The `optimizer` constructor parameter will be used to update the model\n parameters, while the constraint/objective weight matrix (the analogue of\n Lagrange multipliers) will be updated using `constrained_optimizer` (if\n provided) or `optimizer` (if not). Whether the matrix updates are additive\n or multiplicative depends on the derived class.\n\n Args:\n minimization_problem: ConstrainedMinimizationProblem, the problem to\n optimize.\n global_step: as in `tf.train.Optimizer`'s `minimize` method.\n var_list: as in `tf.train.Optimizer`'s `minimize` method.\n gate_gradients: as in `tf.train.Optimizer`'s `minimize` method.\n aggregation_method: as in `tf.train.Optimizer`'s `minimize` method.\n colocate_gradients_with_ops: as in `tf.train.Optimizer`'s `minimize`\n method.\n name: as in `tf.train.Optimizer`'s `minimize` method.\n grad_loss: as in `tf.train.Optimizer`'s `minimize` method.\n\n Returns:\n TensorFlow Op.\n \"\"\"\n objective = minimization_problem.objective\n\n constraints = minimization_problem.constraints\n proxy_constraints = minimization_problem.proxy_constraints\n if proxy_constraints is None:\n proxy_constraints = constraints\n # Flatten both constraints tensors to 1d.\n num_constraints = minimization_problem.num_constraints\n constraints = standard_ops.reshape(constraints, shape=(num_constraints,))\n proxy_constraints = standard_ops.reshape(\n proxy_constraints, shape=(num_constraints,))\n\n # We use a lambda to initialize the state so that, if this function call is\n # inside the scope of a tf.control_dependencies() block, the dependencies\n # will not be applied to the initializer.\n state = standard_ops.Variable(\n lambda: self._initial_state(num_constraints),\n trainable=False,\n name=\"swap_regret_optimizer_state\")\n\n zero_and_constraints = standard_ops.concat(\n (standard_ops.zeros((1,)), constraints), axis=0)\n objective_and_proxy_constraints = standard_ops.concat(\n (standard_ops.expand_dims(objective, 0), proxy_constraints), axis=0)\n\n distribution = self._distribution(state)\n loss = standard_ops.tensordot(distribution, objective_and_proxy_constraints,\n 1)\n matrix_gradient = standard_ops.matmul(\n standard_ops.expand_dims(zero_and_constraints, 1),\n standard_ops.expand_dims(distribution, 0))\n\n update_ops = []\n if self.constraint_optimizer is None:\n # If we don't have a separate constraint_optimizer, then we use\n # self._optimizer for both the update of the model parameters, and that of\n # the internal state.\n grads_and_vars = self.optimizer.compute_gradients(\n loss,\n var_list=var_list,\n gate_gradients=gate_gradients,\n aggregation_method=aggregation_method,\n colocate_gradients_with_ops=colocate_gradients_with_ops,\n grad_loss=grad_loss)\n grads_and_vars.append(\n self._constraint_grad_and_var(state, matrix_gradient))\n update_ops.append(\n self.optimizer.apply_gradients(grads_and_vars, name=\"update\"))\n else:\n # If we have a separate constraint_optimizer, then we use self._optimizer\n # for the update of the model parameters, and self._constraint_optimizer\n # for that of the internal state.\n grads_and_vars = self.optimizer.compute_gradients(\n loss,\n var_list=var_list,\n gate_gradients=gate_gradients,\n aggregation_method=aggregation_method,\n colocate_gradients_with_ops=colocate_gradients_with_ops,\n grad_loss=grad_loss)\n matrix_grads_and_vars = [\n self._constraint_grad_and_var(state, matrix_gradient)\n ]\n\n gradients = [\n gradient for gradient, _ in grads_and_vars + matrix_grads_and_vars\n if gradient is not None\n ]\n with ops.control_dependencies(gradients):\n update_ops.append(\n self.optimizer.apply_gradients(grads_and_vars, name=\"update\"))\n update_ops.append(\n self.constraint_optimizer.apply_gradients(\n matrix_grads_and_vars, name=\"optimizer_state_update\"))\n\n with ops.control_dependencies(update_ops):\n if global_step is None:\n # If we don't have a global step, just project, and we're done.\n return self._projection_op(state, name=name)\n else:\n # If we have a global step, then we need to increment it in addition to\n # projecting.\n projection_op = self._projection_op(state, name=\"project\")\n with ops.colocate_with(global_step):\n global_step_op = state_ops.assign_add(\n global_step, 1, name=\"global_step_increment\")\n return control_flow_ops.group(projection_op, global_step_op, name=name)\n\n\nclass AdditiveSwapRegretOptimizer(_SwapRegretOptimizer):\n \"\"\"A `ConstrainedOptimizer` based on swap-regret minimization.\n\n This `ConstrainedOptimizer` uses the given `tf.train.Optimizer`s to jointly\n minimize over the model parameters, and maximize over constraint/objective\n weight matrix (the analogue of Lagrange multipliers), with the latter\n maximization using additive updates and an algorithm that minimizes swap\n regret.\n\n For more specifics, please refer to:\n\n > Cotter, Jiang and Sridharan. \"Two-Player Games for Efficient Non-Convex\n > Constrained Optimization\".\n > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500)\n\n The formulation used by this optimizer can be found in Definition 2, and is\n discussed in Section 4. It is most similar to Algorithm 2 in Section 4, with\n the differences being that it uses `tf.train.Optimizer`s, instead of SGD, for\n the \"inner\" updates, and performs additive (instead of multiplicative) updates\n of the stochastic matrix.\n \"\"\"\n\n def __init__(self, optimizer, constraint_optimizer=None):\n \"\"\"Constructs a new `AdditiveSwapRegretOptimizer`.\n\n Args:\n optimizer: tf.train.Optimizer, used to optimize the objective and\n proxy_constraints portion of ConstrainedMinimizationProblem. If\n constraint_optimizer is not provided, this will also be used to optimize\n the Lagrange multiplier analogues.\n constraint_optimizer: optional tf.train.Optimizer, used to optimize the\n Lagrange multiplier analogues.\n\n Returns:\n A new `AdditiveSwapRegretOptimizer`.\n \"\"\"\n # TODO(acotter): add a parameter determining the initial values of the\n # matrix elements (like initial_multiplier_radius in\n # MultiplicativeSwapRegretOptimizer).\n super(AdditiveSwapRegretOptimizer, self).__init__(\n optimizer=optimizer, constraint_optimizer=constraint_optimizer)\n\n def _initial_state(self, num_constraints):\n # For an AdditiveSwapRegretOptimizer, the internal state is a tensor of\n # shape (m+1,m+1), where m is the number of constraints, representing a\n # left-stochastic matrix.\n dimension = num_constraints + 1\n # Initialize by putting all weight on the objective, and none on the\n # constraints.\n return standard_ops.concat(\n (standard_ops.ones(\n (1, dimension)), standard_ops.zeros((dimension - 1, dimension))),\n axis=0)\n\n def _stochastic_matrix(self, state):\n return state\n\n def _constraint_grad_and_var(self, state, gradient):\n # TODO(acotter): tf.colocate_with(), if colocate_gradients_with_ops is True?\n return (-gradient, state)\n\n def _projection_op(self, state, name=None):\n with ops.colocate_with(state):\n return state_ops.assign(\n state,\n _project_stochastic_matrix_wrt_euclidean_norm(state),\n name=name)\n\n\nclass MultiplicativeSwapRegretOptimizer(_SwapRegretOptimizer):\n \"\"\"A `ConstrainedOptimizer` based on swap-regret minimization.\n\n This `ConstrainedOptimizer` uses the given `tf.train.Optimizer`s to jointly\n minimize over the model parameters, and maximize over constraint/objective\n weight matrix (the analogue of Lagrange multipliers), with the latter\n maximization using multiplicative updates and an algorithm that minimizes swap\n regret.\n\n For more specifics, please refer to:\n\n > Cotter, Jiang and Sridharan. \"Two-Player Games for Efficient Non-Convex\n > Constrained Optimization\".\n > [https://arxiv.org/abs/1804.06500](https://arxiv.org/abs/1804.06500)\n\n The formulation used by this optimizer can be found in Definition 2, and is\n discussed in Section 4. It is most similar to Algorithm 2 in Section 4, with\n the difference being that it uses `tf.train.Optimizer`s, instead of SGD, for\n the \"inner\" updates.\n \"\"\"\n\n def __init__(self,\n optimizer,\n constraint_optimizer=None,\n minimum_multiplier_radius=1e-3,\n initial_multiplier_radius=None):\n \"\"\"Constructs a new `MultiplicativeSwapRegretOptimizer`.\n\n Args:\n optimizer: tf.train.Optimizer, used to optimize the objective and\n proxy_constraints portion of ConstrainedMinimizationProblem. If\n constraint_optimizer is not provided, this will also be used to optimize\n the Lagrange multiplier analogues.\n constraint_optimizer: optional tf.train.Optimizer, used to optimize the\n Lagrange multiplier analogues.\n minimum_multiplier_radius: float, each element of the matrix will be lower\n bounded by `minimum_multiplier_radius` divided by one plus the number of\n constraints.\n initial_multiplier_radius: float, the initial value of each element of the\n matrix associated with a constraint (i.e. excluding those elements\n associated with the objective) will be `initial_multiplier_radius`\n divided by one plus the number of constraints. Defaults to the value of\n `minimum_multiplier_radius`.\n\n Returns:\n A new `MultiplicativeSwapRegretOptimizer`.\n\n Raises:\n ValueError: If the two radius parameters are inconsistent.\n \"\"\"\n super(MultiplicativeSwapRegretOptimizer, self).__init__(\n optimizer=optimizer, constraint_optimizer=constraint_optimizer)\n\n if (minimum_multiplier_radius <= 0.0) or (minimum_multiplier_radius >= 1.0):\n raise ValueError(\"minimum_multiplier_radius must be in the range (0,1)\")\n if initial_multiplier_radius is None:\n initial_multiplier_radius = minimum_multiplier_radius\n elif (initial_multiplier_radius <\n minimum_multiplier_radius) or (minimum_multiplier_radius > 1.0):\n raise ValueError(\"initial_multiplier_radius must be in the range \"\n \"[minimum_multiplier_radius,1]\")\n\n self._minimum_multiplier_radius = minimum_multiplier_radius\n self._initial_multiplier_radius = initial_multiplier_radius\n\n def _initial_state(self, num_constraints):\n # For a MultiplicativeSwapRegretOptimizer, the internal state is a tensor of\n # shape (m+1,m+1), where m is the number of constraints, representing the\n # element-wise logarithm of a left-stochastic matrix.\n dimension = num_constraints + 1\n # Initialize by putting as much weight as possible on the objective, and as\n # little as possible on the constraints.\n log_initial_one = math.log(1.0 - (self._initial_multiplier_radius *\n (dimension - 1) / (dimension)))\n log_initial_zero = math.log(self._initial_multiplier_radius / dimension)\n return standard_ops.concat(\n (standard_ops.constant(\n log_initial_one, dtype=dtypes.float32, shape=(1, dimension)),\n standard_ops.constant(\n log_initial_zero,\n dtype=dtypes.float32,\n shape=(dimension - 1, dimension))),\n axis=0)\n\n def _stochastic_matrix(self, state):\n return standard_ops.exp(state)\n\n def _constraint_grad_and_var(self, state, gradient):\n # TODO(acotter): tf.colocate_with(), if colocate_gradients_with_ops is True?\n return (-gradient, state)\n\n def _projection_op(self, state, name=None):\n with ops.colocate_with(state):\n # Gets the dimension of the state (num_constraints + 1)--all of these\n # assertions are of things that should be impossible, since the state\n # passed into this method will have the same shape as that returned by\n # _initial_state().\n state_shape = state.get_shape()\n assert state_shape is not None\n assert state_shape.ndims == 2\n assert state_shape[0] == state_shape[1]\n dimension = state_shape[0].value\n assert dimension is not None\n\n minimum_log_multiplier = standard_ops.log(\n self._minimum_multiplier_radius / standard_ops.to_float(dimension))\n\n return state_ops.assign(\n state,\n standard_ops.maximum(\n _project_log_stochastic_matrix_wrt_kl_divergence(state),\n minimum_log_multiplier),\n name=name)\n" ]
[ [ "tensorflow.python.keras.engine.training_eager.predict_loop", "numpy.expand_dims", "tensorflow.python.keras.backend.name_scope", "tensorflow.python.keras.engine.training_eager.test_on_batch", "numpy.asarray", "tensorflow.python.keras.engine.training_utils.prepare_sample_weights", "tensorflow.python.keras.backend.int_shape", "tensorflow.python.keras.backend.placeholder", "tensorflow.python.keras.engine.training_utils.get_metric_function", "tensorflow.python.keras.engine.training_distributed.fit_loop", "tensorflow.python.keras.backend.dtype", "tensorflow.python.keras.backend.function", "tensorflow.python.keras.engine.training_utils.weighted_masked_objective", "tensorflow.python.keras.engine.training_arrays.predict_loop", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.keras.metrics.squeeze_or_expand_dimensions", "tensorflow.python.keras.optimizers.get", "tensorflow.python.keras.backend.image_data_format", "tensorflow.python.keras.engine.training_utils.collect_metrics", "tensorflow.python.keras.engine.training_utils.validate_iterator_input", "tensorflow.python.keras.engine.training_distributed.clone_and_build_model", "tensorflow.python.keras.engine.training_arrays.fit_loop", "tensorflow.python.keras.engine.distributed_training_utils.validate_distributed_dataset_inputs", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.keras.engine.training_utils.has_symbolic_tensors", "tensorflow.python.keras.backend.is_placeholder", "tensorflow.python.keras.engine.distributed_training_utils.set_weights", "tensorflow.python.keras.engine.training_utils.standardize_sample_weights", "tensorflow.python.keras.engine.training_distributed.predict_loop", "tensorflow.python.keras.backend.floatx", "tensorflow.python.ops.weights_broadcast_ops.broadcast_weights", "tensorflow.python.keras.backend.get_session", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.keras.engine.training_generator.fit_generator", "tensorflow.python.keras.engine.training_utils.standardize_class_weights", "tensorflow.python.keras.engine.base_layer.DeferredTensor", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.keras.utils.generic_utils.slice_arrays", "tensorflow.python.keras.losses.get", "tensorflow.python.framework.tensor_util.is_tensor", "tensorflow.python.keras.metrics.get", "tensorflow.python.keras.engine.training_eager.train_on_batch", "tensorflow.python.keras.engine.training_utils.standardize_input_data", "tensorflow.python.keras.engine.training_utils.standardize_weights", "tensorflow.python.keras.engine.training_utils.check_loss_and_target_compatibility", "tensorflow.python.keras.engine.training_eager.test_loop", "tensorflow.python.keras.engine.training_utils.check_array_lengths", "tensorflow.python.keras.engine.training_distributed.test_loop", "tensorflow.python.keras.engine.training_generator.predict_generator", "tensorflow.python.keras.engine.distributed_training_utils.validate_callbacks", "tensorflow.python.keras.engine.training_utils.cast_if_floating_dtype", "tensorflow.python.keras.engine.training_utils.check_steps_argument", "tensorflow.python.keras.backend.is_sparse", "tensorflow.python.keras.backend.learning_phase", "tensorflow.python.keras.engine.training_arrays.test_loop", "tensorflow.python.keras.engine.training_eager.fit_loop", "tensorflow.python.keras.engine.training_generator.evaluate_generator" ], [ "tensorflow.python.keras.layers.Lambda", "tensorflow.python.keras.models.Model", "tensorflow.python.platform.test.main", "numpy.transpose", "numpy.random.uniform", "tensorflow.python.keras.applications.imagenet_utils.preprocess_input", "tensorflow.python.keras.layers.Input" ], [ "tensorflow.python.ops.gen_random_ops.random_uniform", "tensorflow.python.ops.array_ops.split", "tensorflow.python.eager.backprop.GradientTape", "tensorflow.python.framework.ops.device", "tensorflow.python.eager.context.context", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.resource_variable_ops.ResourceVariable", "numpy.arange", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.ops.init_ops.ones_initializer", "tensorflow.python.platform.googletest.main", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.eager.context.graph_mode", "tensorflow.python.ops.embedding_ops.embedding_lookup", "tensorflow.python.eager.backprop.implicit_grad", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ops.array_ops.slice", "tensorflow.python.eager.function.defun", "tensorflow.python.training.adam.AdamOptimizer", "tensorflow.python.eager.backprop.gradients_function", "tensorflow.python.ops.init_ops.zeros_initializer", "numpy.ones", "tensorflow.python.layers.pooling.MaxPooling2D", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.state_ops.assign_add", "tensorflow.python.ops.control_flow_ops.while_loop", "tensorflow.python.ops.standard_ops.reduce_sum", "tensorflow.python.ops.standard_ops.reduce_max", "tensorflow.python.ops.standard_ops.tensordot", "tensorflow.python.ops.standard_ops.expand_dims", "tensorflow.python.ops.standard_ops.not_equal", "tensorflow.python.ops.standard_ops.ones", "tensorflow.python.ops.standard_ops.ones_like", "tensorflow.python.ops.standard_ops.norm", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.standard_ops.exp", "tensorflow.python.ops.standard_ops.abs", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.ops.standard_ops.logical_and", "tensorflow.python.ops.standard_ops.to_float", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.ops.standard_ops.reshape", "tensorflow.python.ops.standard_ops.zeros", "tensorflow.python.ops.standard_ops.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "1.4", "2.2", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "1.0", "2.6", "1.2", "2.10" ] } ]
jkrogager/PyNOT
[ "2514a443079e50c12a13ebbd89a48f91a8d20626" ]
[ "pynot/phot.py" ]
[ "\"\"\"\nFunctions for Imaging Pipeline\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nfrom astropy.io import fits\nfrom astropy.modeling import models, fitting\nfrom astropy.table import Table\nfrom scipy.optimize import curve_fit\nimport os\n\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\nfrom astroquery.sdss import SDSS\n\nimport astroalign as aa\nimport sep\n\nfrom pynot import alfosc\nfrom pynot.functions import get_version_number, mad\nfrom pynot.data.organizer import get_filter\n\n__version__ = get_version_number()\n\n\ndef source_detection(fname, zeropoint=0., threshold=5.0, aperture=10.0, kwargs_bg={}, kwargs_ext={}):\n \"\"\"\n Run source detection in the input image using the python package SEP, based on the SExtractor algorithm.\n\n Parameters\n ----------\n fname : str\n Filename of the FITS image to be analyzed. The image must have at least two extensions:\n the first should be the image in counts, and one should be named ERR holding the associated error image\n\n zeropoint : float [default=0.]\n Magnitude zero-point for the given photometric filter used for the observations.\n By defualt instrument magnitudes will be returned if no zero-point is given.\n\n threshold : float [default=5.0]\n Detection threshold in 'sigmas'.\n\n aperture : float [default=10.]\n Circular aperture radius in pixels.\n\n kwargs_bg : dict\n Parameters to pass to background subtraction (sep.Background()).\n See defition in `default_options_img.yml`\n\n kwargs_ext : dict\n Parameters to pass to source extraction (sep.extract()).\n See defition in `default_options_img.yml`\n\n Returns\n -------\n table_fname : str\n The autogenerated filename of the source catalog. The format is: file-base of the input filename + '_phot.fits'.\n Ex.: fname='alfosc_rband.fits' -> table_fname='alfosc_rband_phot.fits'\n\n segmap_fname : str\n The autogenerated filename of the segmentation map. This image holds the regions associated to each source\n in the source catalog. The format is: file-base of the input filename + '_sep.fits'\n\n output_msg : str\n Log of messages from the function call.\n \"\"\"\n msg = list()\n # get GAIN from header\n data = fits.getdata(fname)\n error_image = fits.getdata(fname, 'ERR')\n hdr = fits.getheader(fname)\n msg.append(\" - Loaded input image: %s\" % fname)\n\n if 'EXPTIME' in hdr:\n exptime = hdr['EXPTIME']\n msg.append(\" - Loaded exposure time from image header: %.1f\" % exptime)\n else:\n exptime = 1.\n msg.append(\"[WARNING] - No exposure time found in image header! Assuming image in counts.\")\n\n data = data * 1.\n error_image = error_image * 1.\n if 'threshold' in kwargs_ext:\n threshold = kwargs_ext.pop('threshold')\n if 'aperture' in kwargs_ext:\n aperture = kwargs_ext.pop('aperture')\n\n bkg = sep.Background(data, **kwargs_bg)\n data_sub = data - bkg\n msg.append(\" - Subtracted sky background\")\n msg.append(\" - Background RMS: %.2e\" % bkg.globalrms)\n data_sub = data_sub.byteswap().newbyteorder()\n error_image = error_image.byteswap().newbyteorder()\n if data_sub.dtype.byteorder != '<':\n data_sub = data_sub.byteswap().newbyteorder()\n error_image = error_image.byteswap().newbyteorder()\n extract_output = sep.extract(data_sub, threshold, err=bkg.globalrms, **kwargs_ext)\n if len(extract_output) == 2:\n objects, segmap = extract_output\n else:\n objects = extract_output\n segmap = None\n N_obj = len(objects)\n msg.append(\" - Detected %i objects\" % N_obj)\n\n # Calculate fixed aperture magnitudes:\n aper_results = sep.sum_circle(data_sub, objects['x'], objects['y'], aperture, err=error_image)\n aper_flux, aper_fluxerr, aper_flag = aper_results\n msg.append(\" - Calculating fluxes within circular aperture of: %i pixels\" % aperture)\n\n # Calculate Kron radius:\n x = objects['x']\n y = objects['y']\n a = objects['a']\n b = objects['b']\n theta = objects['theta']\n kronrad, krflag = sep.kron_radius(data_sub, x, y, a, b, theta, 6.0)\n kronrad[kronrad < 1.] = 1.\n # Sum fluxes in ellipse apertures:\n flux, fluxerr, flag = sep.sum_ellipse(data_sub, x, y, a, b, theta, 2.5*kronrad, subpix=1)\n msg.append(\" - Calculating Kron radii and fluxes within elliptical apertures\")\n # combine flags:\n flag |= krflag\n\n # If the Kron radius is less than r_min (aperture), use aperture fluxes:\n r_min = aperture\n use_circle = kronrad * np.sqrt(b * a) < r_min\n flux[use_circle] = aper_flux[use_circle]\n fluxerr[use_circle] = aper_fluxerr[use_circle]\n flag[use_circle] = aper_flag[use_circle]\n msg.append(\" - Targets with Kron radii below R_min (%.2f) are ignored\" % r_min)\n msg.append(\" - Circular aperture fluxes used instead where R_kron < R_min\")\n if np.sum(use_circle) == 1:\n msg.append(\" - %i source identified with R_kron < R_min\" % np.sum(use_circle))\n else:\n msg.append(\" - %i sources identified with R_kron < R_min\" % np.sum(use_circle))\n\n # Save output table:\n base, ext = os.path.splitext(fname)\n table_fname = base + '_phot.fits'\n object_table = Table(objects)\n object_table['flux_auto'] = flux\n object_table['flux_err_auto'] = fluxerr\n object_table['flux_aper'] = aper_flux\n object_table['flux_err_aper'] = aper_fluxerr\n object_table['R_kron'] = kronrad\n flux[flux <= 0] = 1.\n object_table['mag_auto'] = zeropoint - 2.5*np.log10(flux)\n object_table.write(table_fname, format='fits', overwrite=True)\n msg.append(\" [OUTPUT] - Saved extraction table: %s\" % table_fname)\n\n # Save segmentation map:\n if segmap is not None:\n segmap_fname = base + '_seg.fits'\n seg_hdr = fits.Header()\n seg_hdr['AUTHOR'] = 'PyNOT version %s' % __version__\n seg_hdr['IMAGE'] = fname\n seg_hdr['FILTER'] = get_filter(hdr)\n seg_hdr.add_comment(\"Segmentation map from SEP (SExtractor)\")\n fits.writeto(segmap_fname, segmap, header=seg_hdr, overwrite=True)\n msg.append(\" [OUTPUT] - Saved source segmentation map: %s\" % segmap_fname)\n else:\n segmap_fname = ''\n\n # Plot source identifications:\n fig_fname = base + '_sources.pdf'\n plot_objects(fig_fname, data_sub, objects, threshold=threshold)\n msg.append(\" [OUTPUT] - Saved source identification overview: %s\" % fig_fname)\n msg.append(\"\")\n output_msg = \"\\n\".join(msg)\n\n return table_fname, segmap_fname, output_msg\n\n\ndef plot_objects(fig_fname, data, objects, threshold=5.):\n \"\"\"\n Create a plot of the image and the detected sources from SEP.\n\n Parameters\n ----------\n fig_fname : str\n Filename of the resulting figure\n\n data : np.array, shape (N, M)\n Numpy array of the image data, must be a 2D array.\n\n objects : astropy.table.Table or List[dict]\n List of dictionaries or astropy table holding the object information:\n x, y : x, y positions\n a, b : aperture minor and major axes in pixels\n theta : aperture orientation in radians\n\n threshold : float [default=5.]\n Constract threshold for the image. The color-scale is normalized based on the image\n statistics (median and MAD). The min and max values are -1*MAD and +`threshold`*MAD\n around the median value of the image counts, where MAD is the median absolute deviation.\n\n Returns\n -------\n None\n \"\"\"\n # plot background-subtracted image\n fig, ax = plt.subplots()\n m, s = np.median(data), 1.5*mad(data)\n ax.imshow(data, interpolation='nearest', cmap='gray_r',\n vmin=m-1*s, vmax=m+threshold*s, origin='lower')\n\n # plot an ellipse for each object\n for item in objects:\n e = Ellipse(xy=(item['x'], item['y']),\n width=10*item['a'],\n height=10*item['b'],\n angle=item['theta'] * 180. / np.pi)\n e.set_facecolor('none')\n e.set_edgecolor('red')\n e.set_linewidth(0.8)\n ax.add_artist(e)\n fig.tight_layout()\n fig.savefig(fig_fname)\n\n\ndef load_fits_image(fname):\n \"\"\"Load a FITS image with an associated error extension and an optional data quality MASK.\"\"\"\n with fits.open(fname) as hdu_list:\n image = hdu_list[0].data\n hdr = hdu_list[0].header\n if 'ERR' in hdu_list:\n error = hdu_list['ERR'].data\n else:\n raise TypeError(\"No error image detected\")\n\n if 'MASK' in hdu_list:\n mask = hdu_list['MASK'].data\n else:\n mask = np.zeros_like(image, dtype=bool)\n return image, error, mask, hdr\n\n\ndef measure_seeing(img, centers, size=20, max_obj=10):\n \"\"\"\n Measure the average seeing in an image by fitting a 2D Gaussian to pre-defined point sources.\n\n Parameters\n ----------\n img : np.array, shape(N, M)\n Numpy array of the image to analyze.\n\n centers : list[number, number]\n List of positions of point sources (x, y) in pixels\n\n size : int [default=20]\n Image cutout size. The Gaussian PSF is fitted in a box of size 2*size by 2*size pixels.\n\n max_obj : int [default=10]\n Maximum number of sources to include in the fitting.\n\n Returns\n -------\n fwhm : float\n The average seeing FWHM in pixels.\n\n ratio : float\n The average axis ratio (ellipticity) of the Gaussian PSF.\n\n msg : str\n Output message of the function call.\n If no warnings occurred, this is an emptry string.\n \"\"\"\n X = np.arange(img.shape[1])\n Y = np.arange(img.shape[0])\n sigmas = list()\n ratios = list()\n good_x = (centers[:, 0] > size) & (centers[:, 0] < X.max()-size)\n good_y = (centers[:, 1] > size) & (centers[:, 1] < Y.max()-size)\n if np.sum(good_x & good_y) < 2:\n msg = \"[WARNING] - Not enough sources to measure seeing.\"\n return (-1, -1, msg)\n max_obj = min(max_obj, np.sum(good_x & good_y))\n idx = np.random.choice(np.arange(len(centers))[good_x & good_y], max_obj, replace=False)\n for x_cen, y_cen in centers[idx]:\n x1, x2 = int(x_cen)-size, int(x_cen)+size\n y1, y2 = int(y_cen)-size, int(y_cen)+size\n cutout = img[y1:y2, x1:x2]\n x, y = np.meshgrid(X[x1:x2], Y[y1:y2])\n A = img[int(y_cen), int(x_cen)]\n p_init = models.Gaussian2D(amplitude=A, x_mean=x_cen, y_mean=y_cen, x_stddev=5, y_stddev=5, theta=0)\n try:\n fitter = fitting.LevMarLSQFitter()\n except TypeError:\n continue\n p_opt = fitter(p_init, x, y, cutout-np.median(cutout))\n sigma_x = p_opt.x_stddev\n sigma_y = p_opt.y_stddev\n sig = np.sqrt(sigma_x**2 + sigma_y**2)\n ba = min(sigma_x, sigma_y) / max(sigma_x, sigma_y)\n sigmas.append(sig)\n ratios.append(ba)\n\n if len(sigmas) < 2:\n msg = \"[WARNING] - Not enough sources to measure seeing.\"\n return (-1, -1, msg)\n\n fwhm = np.median(sigmas) * 2.35\n ratio = np.median(ratios)\n msg = \"\"\n return (fwhm, ratio, msg)\n\n\ndef save_file_log(log_name, image_log, target_hdr):\n with open(log_name, 'w') as out:\n out.write(\"# PyNOT Combination Log of Target: %s\\n\" % target_hdr['OBJECT'])\n out.write(\"# Filter: %s\\n\" % get_filter(target_hdr))\n out.write(\"# Col 1: Filename\\n\")\n out.write(\"# Col 2: FWHM / pixels (seeing)\\n\")\n out.write(\"# Col 3: PSF axis ratio (minor/major)\\n\")\n out.write(\"# Col 4: Exp. Time / seconds\\n\")\n out.write(\"# \" + 40*\"-\" + \"\\n\")\n for line in image_log:\n out.write(\" %s %.1f %5.2f %6.1f\\n\" % tuple(line))\n\n\ndef image_combine(corrected_images, output='', log_name='', fringe_image='', method='weighted', max_control_points=50, detection_sigma=5, min_area=9):\n \"\"\"\n Register and combine a list of FITS images using affine transformation.\n\n Parameters\n ----------\n corrected_images : List[str]\n List of input filenames of `corrected` images, i.e., bias, flat corrected\n and trimmed for filter/aperture vignetting.\n\n output : str [default='']\n Output filename of the combined image. If not given, it is generated from the OBJECT keyword of the FITS header.\n\n log_name : str [default='']\n Filename of the combination log. This table holds the average seeing FWHM, PSF ellipticity, and exposure time\n for each image in the input list.\n\n fringe_image : str [default='']\n Filename of the fringe image (FITS format) from `pynot.create_fringe_image`.\n If given, this image will be subtracted from each input image before combination.\n\n method : str [default='weighted']\n Method for image combination: mean, median or weighted.\n By default an inverse-variance weighting is used.\n\n max_control_points : int [default=50]\n Maximum number of control point-sources to find the transformation.\n A lower number will converge faster but may result in a less robust image registration.\n\n detection_sigma : float [default=5.]\n Detection threshold for control points in units of standard deviations of the sky background.\n\n min_area : int [default=9]\n Minimum number of connected pixels to be considered a source\n\n Returns\n -------\n output_msg : str\n Log of messages from the function call.\n \"\"\"\n msg = list()\n if fringe_image != '':\n norm_sky = fits.getdata(fringe_image)\n msg.append(\" - Loaded normalized fringe image: %s\" % fringe_image)\n else:\n norm_sky = 1.\n target_fname = corrected_images[0]\n target, target_err, target_mask, target_hdr = load_fits_image(target_fname)\n target = target - norm_sky*np.median(target)\n exptime = target_hdr['EXPTIME']\n target /= exptime\n target_err /= exptime\n target_hdr['BUNIT'] = 'count / s'\n msg.append(\" - Aligning all images to reference: %s\" % target_fname)\n\n msg.append(\" - Registering input images:\")\n shifted_images = [target]\n shifted_vars = [target_err**2]\n target = target.byteswap().newbyteorder()\n if target.dtype.byteorder != '<':\n target = target.byteswap().newbyteorder()\n final_exptime = exptime\n image_log = list()\n if len(corrected_images) > 1:\n for fname in corrected_images[1:]:\n msg.append(\" - Input image: %s\" % fname)\n source, source_err, source_mask, hdr_i = load_fits_image(fname)\n source = source - norm_sky*np.median(source)\n source /= hdr_i['EXPTIME']\n source_err /= hdr_i['EXPTIME']\n final_exptime += hdr_i['EXPTIME']\n try:\n transf, (coords) = aa.find_transform(source, target,\n max_control_points=max_control_points,\n detection_sigma=detection_sigma,\n min_area=min_area)\n except:\n msg.append(\" [ERROR] - Failed to find image transformation!\")\n msg.append(\" - Skipping image\")\n continue\n\n source = source.byteswap().newbyteorder()\n source_err = source_err.byteswap().newbyteorder()\n source_mask = source_mask.byteswap().newbyteorder()\n if source.dtype.byteorder != '<':\n source = source.byteswap().newbyteorder()\n if source_err.dtype.byteorder != '<':\n source_err = source_err.byteswap().newbyteorder()\n if source_mask.dtype.byteorder != '<':\n source_mask = source_mask.byteswap().newbyteorder()\n\n registered_image, _ = aa.apply_transform(transf, source, target, fill_value=0)\n registered_error, _ = aa.apply_transform(transf, source_err, target, fill_value=0)\n registered_mask, _ = aa.apply_transform(transf, source_mask, target, fill_value=0)\n target_mask += 1 * (registered_mask > 0)\n registered_error[registered_error == 0] = np.mean(registered_error)*10\n shifted_images.append(registered_image)\n shifted_vars.append(registered_error**2)\n source_list, target_list = coords\n if len(image_log) == 0:\n fwhm, ratio, seeing_msg = measure_seeing(target, target_list)\n image_log.append([os.path.basename(target_fname), fwhm, ratio, exptime])\n if seeing_msg:\n msg.append(seeing_msg)\n fwhm, ratio, seeing_msg = measure_seeing(source, source_list)\n if seeing_msg:\n msg.append(seeing_msg)\n image_log.append([os.path.basename(fname), fwhm, ratio, hdr_i['EXPTIME']])\n\n if log_name == '':\n filter_name = alfosc.filter_translate[get_filter(target_hdr)]\n log_name = 'filelist_%s_%s.txt' % (target_hdr['OBJECT'], filter_name)\n save_file_log(log_name, image_log, target_hdr)\n msg.append(\" [OUTPUT] - Saved file log and image stats: %s\" % log_name)\n\n if method == 'median':\n final_image = np.nanmedian(shifted_images, axis=0)\n final_error = np.sqrt(np.nanmean(shifted_vars, axis=0))\n target_hdr['COMBINE'] = \"Median\"\n elif method == 'mean':\n final_image = np.nanmean(shifted_images, axis=0)\n final_error = np.sqrt(np.nanmean(shifted_vars, axis=0))\n target_hdr['COMBINE'] = \"Mean\"\n else:\n w = 1./np.array(shifted_vars)\n shifted_images = np.array(shifted_images)\n final_image = np.nansum(w*shifted_images, axis=0) / np.sum(w, axis=0)\n final_error = np.sqrt(1. / np.nansum(w, axis=0))\n target_hdr['COMBINE'] = \"Inverse Variance Weighted\"\n final_mask = 1 * (target_mask > 0)\n else:\n final_image = target\n final_error = target_err\n final_mask = target_mask\n target_hdr['COMBINE'] = \"None\"\n\n target_hdr['NCOMBINE'] = len(shifted_images)\n target_hdr['EXPTIME'] = final_exptime / len(shifted_images)\n # Fix NaN values from negative pixel values:\n err_NaN = np.isnan(final_error)\n final_error[err_NaN] = np.nanmean(final_error)*100\n msg.append(\" - Correcting NaNs in noise image: %i pixel(s)\" % np.sum(err_NaN))\n target_hdr['DATAMIN'] = np.nanmin(final_image)\n target_hdr['DATAMAX'] = np.nanmax(final_image)\n target_hdr['EXTNAME'] = 'DATA'\n target_hdr['AUTHOR'] = 'PyNOT version %s' % __version__\n\n mask_hdr = fits.Header()\n mask_hdr.add_comment(\"0 = Good Pixels\")\n mask_hdr.add_comment(\"1 = Cosmic Ray Hits\")\n\n if output == '':\n output = \"combined_%s.fits\" % target_hdr['OBJECT']\n\n sci_ext = fits.PrimaryHDU(final_image, header=target_hdr)\n err_ext = fits.ImageHDU(final_error, header=target_hdr, name='ERR')\n mask_ext = fits.ImageHDU(final_mask, header=mask_hdr, name='MASK')\n output_HDU = fits.HDUList([sci_ext, err_ext, mask_ext])\n output_HDU.writeto(output, overwrite=True)\n msg.append(\" - Successfully combined the images\")\n msg.append(\" [OUTPUT] - Saving output: %s\" % output)\n msg.append(\"\")\n output_msg = \"\\n\".join(msg)\n return output_msg\n\n\ndef plot_image2D(fname, image, vmin=-2, vmax=2):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n med = np.median(image)\n s = mad(image)\n im = ax.imshow(image, origin='lower', vmin=med+vmin*s, vmax=med+vmax*s)\n fig.colorbar(im)\n fig.tight_layout()\n fig.savefig(fname)\n\n\ndef create_fringe_image(input_filenames, output='', fig_fname='', threshold=3.0):\n \"\"\"\n Create a normalized average fringe image for a list of images taken with the same filter.\n\n Parameters\n ----------\n input_filenames : str\n List of FITS filenames of images taken in the same photometric band.\n\n output : str [default='']\n Output filename of the fringe image.\n\n fig_fname : str [default='']\n Output filename of the diagnostic figure showing the normalized fringe image.\n\n threshold : float [default=3.]\n Threshold for source rejection in the image stacking in units of the standard deviation\n of the sky background (estimated via median absolute deviation).\n\n Returns\n -------\n output_msg : str\n Log of messages from the function call.\n \"\"\"\n msg = list()\n hdr = fits.getheader(input_filenames[0])\n img_list = [fits.getdata(fname) for fname in input_filenames]\n exptimes = [fits.getheader(fname)['EXPTIME'] for fname in input_filenames]\n msg.append(\" - Loaded input images\")\n mask = [np.fabs(im-np.median(im)) < threshold*mad(im) for im in img_list]\n msg.append(\" - Created image mask using threshold: %.2f\" % threshold)\n\n N = np.sum(mask, 0)\n skysum = np.sum([im*m/t for im, m, t in zip(img_list, mask, exptimes)], axis=0)\n skysum[N == 0] = np.median(skysum)\n N[N == 0] = 1\n sky = skysum / N\n norm_sky = sky / np.median(sky)\n msg.append(\" - Created normalized fringe image\")\n\n if fig_fname:\n plot_image2D(fig_fname, norm_sky, vmin=-2, vmax=2)\n msg.append(\" [OUTPUT] - Saving figure: %s\" % fig_fname)\n\n if output == '':\n output = \"fringe_%s.fits\" % hdr['OBJECT']\n hdr['OBJECT'] = 'Fringe Image'\n hdr['EXTNAME'] = 'MODEL'\n hdr.add_comment('Average Fringe image, median normalized')\n fits.writeto(output, norm_sky, header=hdr, overwrite=True)\n msg.append(\" [OUTPUT] - Saving output: %s\" % output)\n msg.append(\"\")\n output_msg = \"\\n\".join(msg)\n return output_msg\n\n\n\ndef match_phot_catalogs(sep, phot, match_radius=1.):\n \"\"\"\n Match a source catalog from SEP to a photometric catalog `phot`.\n Both catalogs must include columns 'ra' and 'dec'.\n\n Parameters\n ----------\n match_radius : float [default=1.0]\n Matching radius in arcseconds\n\n Returns\n -------\n matched_sep : astropy.table.Table\n An astropy table of sources in the SEP source catalog that have matches\n in the reference `phot` catalog.\n\n matched_phot : astropy.table.Table\n An astropy table of sources in the reference `phot` catalog that have matches\n in the SEP source catalog.\n \"\"\"\n matched_sep = list()\n matched_phot = list()\n refs = np.array([phot['ra'], phot['dec']]).T\n for row in sep:\n xy = np.array([row['ra'], row['dec']])\n dist = np.sqrt(np.sum((refs - xy)**2, axis=1))\n index = np.argmin(dist)\n if np.min(dist) < match_radius/3600.:\n matched_phot.append(np.array(phot[index]))\n matched_sep.append(np.array(row))\n matched_sep = np.array(matched_sep)\n matched_phot = np.array(matched_phot)\n return Table(matched_sep), Table(matched_phot)\n\n\ndef get_sdss_catalog(ra, dec, radius=4.):\n \"\"\"Download the SDSS photometry using astroquery for a circular region of radius in deg.\"\"\"\n catalog_fname = 'sdss_phot_%.2f%+.2f.csv' % (ra, dec)\n fields = ['ra', 'dec', 'psfMag_u', 'psfMag_g', 'psfMag_r', 'psfMag_i', 'psfMag_z',\n 'psfMagErr_u', 'psfMagErr_g', 'psfMagErr_r', 'psfMagErr_i', 'psfMagErr_z']\n field_center = SkyCoord(ra, dec, frame='icrs', unit='deg')\n sdss_result = SDSS.query_region(field_center, radius*u.arcmin, photoobj_fields=fields)\n if sdss_result is not None:\n sdss_result.write(catalog_fname, format='ascii.csv', overwrite=True)\n return sdss_result\n\n\n\next_coeffs = {'u': 0.517,\n 'g': 0.165,\n 'r': 0.0754,\n 'i': 0.0257,\n 'z': 0.0114}\n\ndef flux_calibration_sdss(img_fname, sep_fname, fig_fname='', q_lim=0.8, kappa=3, match_radius=1.):\n \"\"\"\n Self-calibration of magnitude zero point using SDSS photometry as reference\n\n Parameters\n ----------\n img_fname : string\n Filename of WCS calibrated image (_wcs.fits)\n\n sep_fname : string\n Filename of the source extraction table (_phot.fits)\n\n fig_fname : string\n Filename of the diagnostic figure. Autogenerated by default.\n\n q_lim : float [default=0.8]\n Reject elliptical sources with axis ratio < `q_lim`.\n Axis ratio is defined as minor/major.\n\n kappa : float [default=3]\n Threshold for projected distance filtering. Sources are rejected if the distance differs\n more then `kappa` times the median absolute deviation from the median of all distances.\n\n match_radius : float [default=1]\n Matching radius between SDSS sources and image sources\n\n Returns\n -------\n output_msg : string\n Log of messages from the function call.\n \"\"\"\n # -- Get SDSS catalog\n msg = list()\n\n hdr = fits.getheader(img_fname)\n msg.append(\" - Loaded image: %s\" % img_fname)\n radius = np.sqrt(hdr['CD1_1']**2 + hdr['CD1_2']**2)*60 * hdr['NAXIS1'] / np.sqrt(2)\n msg.append(\" - Downloading SDSS photometric catalog...\")\n try:\n sdss_cat = get_sdss_catalog(hdr['CRVAL1'], hdr['CRVAL2'], radius)\n except:\n msg.append(\" [ERROR] - Could not connect to SDSS server. Check your internet connection.\")\n msg.append(\"\")\n return \"\\n\".join(msg)\n\n def line(x, zp):\n return zp + x\n\n if sdss_cat is None:\n msg.append(\" [ERROR] - No data found in SDSS. No zero point calculated\")\n msg.append(\"\")\n return \"\\n\".join(msg)\n\n airmass = hdr['AIRMASS']\n filter = alfosc.filter_translate[alfosc.get_filter(hdr)]\n if 'SDSS' in filter:\n band = filter.split('_')[0]\n else:\n msg.append(\" [ERROR] - The image was not taken with an SDSS filter. No zero point calculated\")\n msg.append(\"\")\n return \"\\n\".join(msg)\n\n\n # For r-band: (measured from La Palma extinction curve)\n mag_key = 'psfMag_%s' % band\n mag_err_key = 'psfMagErr_%s' % band\n good = (sdss_cat[mag_key] > 0) & (sdss_cat[mag_key] < 30)\n sdss_cat = sdss_cat[good]\n\n # Load SEP filename:\n try:\n sep_cat = Table.read(sep_fname)\n sep_hdr = fits.getheader(sep_fname)\n msg.append(\" - Loaded SEP source table: %s\" % sep_fname)\n except (FileNotFoundError, OSError):\n msg.append(\" [ERROR] - Could not load SEP source table: %s\" % sep_fname)\n msg.append(\"\")\n return \"\\n\".join(msg)\n\n if 'MAG_ZP' in sep_hdr:\n msg.append(\"[WARNING] - The source table has already been flux calibrated by PyNOT\")\n msg.append(\" - Terminating task...\")\n msg.append(\"\")\n return \"\\n\".join(msg)\n\n axis_ratio = sep_cat['b']/sep_cat['a']\n # Select only 'round' sources:\n sep_points = sep_cat[axis_ratio > q_lim]\n\n # Match catalogs:\n match_sep, match_sdss = match_phot_catalogs(sep_points, sdss_cat)\n msg.append(\" - Cross matched source catalog\")\n\n mag = match_sdss[mag_key]\n mag_err = match_sdss[mag_err_key]\n m_inst = match_sep['mag_auto']\n k = ext_coeffs[band]\n\n # Get first estimate using the median:\n zp0, _ = curve_fit(line, m_inst+k*airmass, mag, p0=[27], sigma=mag_err)\n\n # Filter outliers:\n cut = np.abs(zp0 + m_inst + k*airmass - mag) < kappa*mad(zp0 + m_inst + k*airmass - mag)\n cut &= (mag < 20.1) & (mag > 15)\n\n # Get weighted average zero point:\n w = 1./mag_err[cut]**2\n zp = np.sum((mag[cut] - m_inst[cut] - k*airmass) * w) / np.sum(w)\n msg.append(\" - Calculating zero point in SDSS %s band using %i sources\" % (band, len(w)))\n\n # Zero point dispersion:\n zp_err = np.std(mag[cut] - zp - m_inst[cut] - k*airmass)\n msg.append(\" - Zero Point = %.3f ± %.3f mag\" % (zp, zp_err))\n\n sep_cat['mag_auto'] += zp\n sep_cat.write(sep_fname, overwrite=True)\n with fits.open(sep_fname, 'update') as sep_file:\n sep_file[0].header.add_comment(\"Self-calibration of mag. zero point using SDSS\")\n sep_file[0].header['MAG_ZP'] = (np.round(zp, 3), \"Magnitude zero point (AB mag)\")\n sep_file[0].header['ZP_ERR'] = (np.round(zp_err, 3), \"Uncertainty on magnitude zero point (AB mag)\")\n msg.append(\" [OUTPUT] - Updating magnitudes in source table: %s\" % sep_fname)\n\n # -- Plot the zero point for visual aid:\n base, _ = os.path.splitext(os.path.basename(img_fname))\n dirname = os.path.dirname(img_fname)\n if fig_fname == '':\n fig_fname = 'zero_point_' + base + '.pdf'\n fig_fname = os.path.join(dirname, fig_fname)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.errorbar(m_inst, mag, 3*mag_err, ls='', marker='.', color='k', alpha=0.8)\n ax.plot(m_inst[cut], mag[cut], ls='', marker='o', color='b', alpha=0.7)\n ax.plot(np.sort(m_inst), zp + np.sort(m_inst) + k*airmass, ls='--', color='crimson',\n label='ZP = %.2f ± %.2f' % (zp, zp_err))\n ax.set_ylim(np.min(mag)-0.2, np.max(mag)+0.5)\n ax.set_xlabel(\"Instrument Magnitude\")\n ax.set_ylabel(\"Reference SDSS Magnitude (r-band)\")\n ax.legend()\n ax.tick_params(which='both', top=False, right=False)\n fig.tight_layout()\n fig.savefig(fig_fname)\n msg.append(\" [OUTPUT] - Saving diagnostic figure: %s\" % fig_fname)\n\n # -- Update header in FITS image:\n with fits.open(img_fname) as hdu_list:\n hdu_list['DATA'].header.add_comment(\"Self-calibration of mag. zero point using SDSS\")\n hdu_list['DATA'].header['MAG_ZP'] = (np.round(zp, 3), \"Magnitude zero point (AB mag)\")\n hdu_list['DATA'].header['ZP_ERR'] = (np.round(zp_err, 3), \"Uncertainty on magnitude zero point (AB mag)\")\n hdu_list.writeto(img_fname, overwrite=True)\n\n msg.append(\" [OUTPUT] - Updating header of input image: %s\" % img_fname)\n msg.append(\" - MAG_ZP = %10.3f / %s\" % (zp, \"Magnitude zero point (AB mag)\"))\n msg.append(\" - ZP_ERR = %10.3f / %s\" % (zp_err, \"Uncertainty on magnitude zero point (AB mag)\"))\n msg.append(\"\")\n return \"\\n\".join(msg)\n" ]
[ [ "numpy.nanmax", "numpy.nanmedian", "numpy.sqrt", "numpy.nanmin", "numpy.round", "numpy.max", "numpy.argmin", "numpy.nanmean", "numpy.zeros_like", "numpy.mean", "scipy.optimize.curve_fit", "numpy.arange", "numpy.std", "numpy.nansum", "matplotlib.pyplot.figure", "numpy.min", "numpy.isnan", "numpy.median", "numpy.log10", "numpy.meshgrid", "numpy.array", "numpy.sum", "matplotlib.patches.Ellipse", "numpy.abs", "matplotlib.pyplot.subplots", "numpy.sort" ] ]
[ { "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": [] } ]
RobinVogel/metric-learn
[ "a30471424d35b0ef47582751fa6acea7b3a3bce5", "a30471424d35b0ef47582751fa6acea7b3a3bce5" ]
[ "test/metric_learn_test.py", "metric_learn/nca.py" ]
[ "import unittest\nimport re\nimport pytest\nimport numpy as np\nimport scipy\nfrom scipy.optimize import check_grad, approx_fprime\nfrom six.moves import xrange\nfrom sklearn.metrics import pairwise_distances, euclidean_distances\nfrom sklearn.datasets import (load_iris, make_classification, make_regression,\n make_spd_matrix)\nfrom numpy.testing import (assert_array_almost_equal, assert_array_equal,\n assert_allclose)\nfrom sklearn.utils.testing import assert_warns_message\nfrom sklearn.exceptions import ConvergenceWarning, ChangedBehaviorWarning\nfrom sklearn.utils.validation import check_X_y\ntry:\n from inverse_covariance import quic\n assert(quic)\nexcept ImportError:\n HAS_SKGGM = False\nelse:\n HAS_SKGGM = True\nfrom metric_learn import (LMNN, NCA, LFDA, Covariance, MLKR, MMC,\n LSML_Supervised, ITML_Supervised, SDML_Supervised,\n RCA_Supervised, MMC_Supervised, SDML, RCA, ITML,\n LSML)\n# Import this specially for testing.\nfrom metric_learn.constraints import wrap_pairs\nfrom metric_learn.lmnn import _sum_outer_products\n\n\ndef class_separation(X, labels):\n unique_labels, label_inds = np.unique(labels, return_inverse=True)\n ratio = 0\n for li in xrange(len(unique_labels)):\n Xc = X[label_inds == li]\n Xnc = X[label_inds != li]\n ratio += pairwise_distances(Xc).mean() / pairwise_distances(Xc, Xnc).mean()\n return ratio / len(unique_labels)\n\n\nclass MetricTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n # runs once per test class\n iris_data = load_iris()\n self.iris_points = iris_data['data']\n self.iris_labels = iris_data['target']\n np.random.seed(1234)\n\n\nclass TestCovariance(MetricTestCase):\n def test_iris(self):\n cov = Covariance()\n cov.fit(self.iris_points)\n\n csep = class_separation(cov.transform(self.iris_points), self.iris_labels)\n # deterministic result\n self.assertAlmostEqual(csep, 0.72981476)\n\n def test_singular_returns_pseudo_inverse(self):\n \"\"\"Checks that if the input covariance matrix is singular, we return\n the pseudo inverse\"\"\"\n X, y = load_iris(return_X_y=True)\n # We add a virtual column that is a linear combination of the other\n # columns so that the covariance matrix will be singular\n X = np.concatenate([X, X[:, :2].dot([[2], [3]])], axis=1)\n cov_matrix = np.cov(X, rowvar=False)\n covariance = Covariance()\n covariance.fit(X)\n pseudo_inverse = covariance.get_mahalanobis_matrix()\n # here is the definition of a pseudo inverse according to wikipedia:\n assert_allclose(cov_matrix.dot(pseudo_inverse).dot(cov_matrix),\n cov_matrix)\n assert_allclose(pseudo_inverse.dot(cov_matrix).dot(pseudo_inverse),\n pseudo_inverse)\n\n\nclass TestLSML(MetricTestCase):\n def test_iris(self):\n lsml = LSML_Supervised(num_constraints=200)\n lsml.fit(self.iris_points, self.iris_labels)\n\n csep = class_separation(lsml.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.8) # it's pretty terrible\n\n def test_deprecation_num_labeled(self):\n # test that a deprecation message is thrown if num_labeled is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n lsml_supervised = LSML_Supervised(num_labeled=np.inf)\n msg = ('\"num_labeled\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0')\n assert_warns_message(DeprecationWarning, msg, lsml_supervised.fit, X, y)\n\n def test_changed_behaviour_warning(self):\n # test that a ChangedBehavior warning is thrown about the init, if the\n # default parameters are used.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n lsml_supervised = LSML_Supervised()\n msg = (\"Warning, no prior was set (`prior=None`). As of version 0.5.0, \"\n \"the default prior will now be set to \"\n \"'identity', instead of 'covariance'. If you still want to use \"\n \"the inverse of the covariance matrix as a prior, \"\n \"set prior='covariance'. This warning will disappear in \"\n \"v0.6.0, and `prior` parameter's default value will be set to \"\n \"'identity'.\")\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n lsml_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n pairs = np.array([[[-10., 0.], [10., 0.], [-5., 3.], [5., 0.]],\n [[0., 50.], [0., -60], [-10., 0.], [10., 0.]]])\n lsml = LSML()\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n lsml.fit(pairs)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_deprecation_random_state(self):\n # test that a deprecation message is thrown if random_state is set at\n # fit time\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n lsml_supervised = LSML_Supervised()\n msg = ('\"random_state\" parameter in the `fit` function is '\n 'deprecated. Set `random_state` at initialization '\n 'instead (when instantiating a new `LSML_Supervised` '\n 'object).')\n with pytest.warns(DeprecationWarning) as raised_warning:\n lsml_supervised.fit(X, y, random_state=np.random)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning_random_state(self):\n # test that a ChangedBehavior warning is thrown if the random_state is\n # not set in fit.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n lsml_supervised = LSML_Supervised()\n msg = ('As of v0.5.0, `LSML_Supervised` now uses the '\n '`random_state` given at initialization to sample '\n 'constraints, not the default `np.random` from the `fit` '\n 'method, since this argument is now deprecated. '\n 'This warning will disappear in v0.6.0.')\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n lsml_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n\nclass TestITML(MetricTestCase):\n def test_iris(self):\n itml = ITML_Supervised(num_constraints=200)\n itml.fit(self.iris_points, self.iris_labels)\n\n csep = class_separation(itml.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.2)\n\n def test_deprecation_num_labeled(self):\n # test that a deprecation message is thrown if num_labeled is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n itml_supervised = ITML_Supervised(num_labeled=np.inf)\n msg = ('\"num_labeled\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0')\n assert_warns_message(DeprecationWarning, msg, itml_supervised.fit, X, y)\n\n def test_deprecation_bounds(self):\n # test that a deprecation message is thrown if bounds is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n itml_supervised = ITML_Supervised(bounds=None)\n msg = ('\"bounds\" parameter from initialization is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0. Use the \"bounds\" parameter of this '\n 'fit method instead.')\n assert_warns_message(DeprecationWarning, msg, itml_supervised.fit, X, y)\n\n def test_deprecation_A0(self):\n # test that a deprecation message is thrown if A0 is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n itml_supervised = ITML_Supervised(A0=np.ones_like(X))\n msg = ('\"A0\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n 'removed in 0.6.0. Use \"prior\" instead.')\n with pytest.warns(DeprecationWarning) as raised_warning:\n itml_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n itml = ITML(A0=np.ones_like(X))\n with pytest.warns(DeprecationWarning) as raised_warning:\n itml.fit(pairs, y_pairs)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_deprecation_random_state(self):\n # test that a deprecation message is thrown if random_state is set at\n # fit time\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n itml_supervised = ITML_Supervised()\n msg = ('\"random_state\" parameter in the `fit` function is '\n 'deprecated. Set `random_state` at initialization '\n 'instead (when instantiating a new `ITML_Supervised` '\n 'object).')\n with pytest.warns(DeprecationWarning) as raised_warning:\n itml_supervised.fit(X, y, random_state=np.random)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning_random_state(self):\n # test that a ChangedBehavior warning is thrown if the random_state is\n # not set in fit.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n itml_supervised = ITML_Supervised()\n msg = ('As of v0.5.0, `ITML_Supervised` now uses the '\n '`random_state` given at initialization to sample '\n 'constraints, not the default `np.random` from the `fit` '\n 'method, since this argument is now deprecated. '\n 'This warning will disappear in v0.6.0.')\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n itml_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n\[email protected]('bounds', [None, (20., 100.), [20., 100.],\n np.array([20., 100.]),\n np.array([[20., 100.]]),\n np.array([[20], [100]])])\ndef test_bounds_parameters_valid(bounds):\n \"\"\"Asserts that we can provide any array-like of two elements as bounds,\n and that the attribute bound_ is a numpy array\"\"\"\n\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n itml = ITML()\n itml.fit(pairs, y_pairs, bounds=bounds)\n\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n itml_supervised = ITML_Supervised()\n itml_supervised.fit(X, y, bounds=bounds)\n\n\[email protected]('bounds', ['weird', ['weird1', 'weird2'],\n np.array([1, 2, 3])])\ndef test_bounds_parameters_invalid(bounds):\n \"\"\"Assert that if a non array-like is put for bounds, or an array-like\n of length different than 2, an error is returned\"\"\"\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n itml = ITML()\n with pytest.raises(Exception):\n itml.fit(pairs, y_pairs, bounds=bounds)\n\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n itml_supervised = ITML_Supervised()\n with pytest.raises(Exception):\n itml_supervised.fit(X, y, bounds=bounds)\n\n\nclass TestLMNN(MetricTestCase):\n def test_iris(self):\n lmnn = LMNN(k=5, learn_rate=1e-6, verbose=False)\n lmnn.fit(self.iris_points, self.iris_labels)\n\n csep = class_separation(lmnn.transform(self.iris_points),\n self.iris_labels)\n self.assertLess(csep, 0.25)\n\n def test_loss_grad_lbfgs(self):\n \"\"\"Test gradient of loss function\n Assert that the gradient is almost equal to its finite differences\n approximation.\n \"\"\"\n rng = np.random.RandomState(42)\n X, y = make_classification(random_state=rng)\n L = rng.randn(rng.randint(1, X.shape[1] + 1), X.shape[1])\n lmnn = LMNN()\n\n k = lmnn.k\n reg = lmnn.regularization\n\n X, y = lmnn._prepare_inputs(X, y, dtype=float,\n ensure_min_samples=2)\n num_pts, n_components = X.shape\n unique_labels, label_inds = np.unique(y, return_inverse=True)\n lmnn.labels_ = np.arange(len(unique_labels))\n lmnn.components_ = np.eye(n_components)\n\n target_neighbors = lmnn._select_targets(X, label_inds)\n\n # sum outer products\n dfG = _sum_outer_products(X, target_neighbors.flatten(),\n np.repeat(np.arange(X.shape[0]), k))\n\n # initialize L\n def loss_grad(flat_L):\n return lmnn._loss_grad(X, flat_L.reshape(-1, X.shape[1]), dfG,\n k, reg, target_neighbors, label_inds)\n\n def fun(x):\n return loss_grad(x)[1]\n\n def grad(x):\n return loss_grad(x)[0].ravel()\n\n # compute relative error\n epsilon = np.sqrt(np.finfo(float).eps)\n rel_diff = (check_grad(fun, grad, L.ravel()) /\n np.linalg.norm(approx_fprime(L.ravel(), fun, epsilon)))\n np.testing.assert_almost_equal(rel_diff, 0., decimal=5)\n\n def test_changed_behaviour_warning(self):\n # test that a ChangedBehavior warning is thrown about the init, if the\n # default parameters are used.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n lmnn = LMNN(k=2)\n msg = (\"Warning, no init was set (`init=None`). As of version 0.5.0, \"\n \"the default init will now be set to 'auto', instead of the \"\n \"previous identity matrix. If you still want to use the identity \"\n \"matrix as before, set init='identity'. This warning \"\n \"will disappear in v0.6.0, and `init` parameter's default value \"\n \"will be set to 'auto'.\")\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n lmnn.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_deprecation_use_pca(self):\n # test that a DeprecationWarning is thrown about use_pca, if the\n # default parameters are used.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n lmnn = LMNN(k=2, use_pca=True)\n msg = ('\"use_pca\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0.')\n assert_warns_message(DeprecationWarning, msg, lmnn.fit, X, y)\n\n\ndef test_loss_func(capsys):\n \"\"\"Test the loss function (and its gradient) on a simple example,\n by comparing the results with the actual implementation of metric-learn,\n with a very simple (but nonperformant) implementation\"\"\"\n\n # toy dataset to use\n X, y = make_classification(n_samples=10, n_classes=2,\n n_features=6,\n n_redundant=0, shuffle=True,\n scale=[1, 1, 20, 20, 20, 20], random_state=42)\n\n def hinge(a):\n if a > 0:\n return a, 1\n else:\n return 0, 0\n\n def loss_fn(L, X, y, target_neighbors, reg):\n L = L.reshape(-1, X.shape[1])\n Lx = np.dot(X, L.T)\n loss = 0\n total_active = 0\n grad = np.zeros_like(L)\n for i in range(X.shape[0]):\n for j in target_neighbors[i]:\n loss += (1 - reg) * np.sum((Lx[i] - Lx[j]) ** 2)\n grad += (1 - reg) * np.outer(Lx[i] - Lx[j], X[i] - X[j])\n for l in range(X.shape[0]):\n if y[i] != y[l]:\n hin, active = hinge(1 + np.sum((Lx[i] - Lx[j])**2) -\n np.sum((Lx[i] - Lx[l])**2))\n total_active += active\n if active:\n loss += reg * hin\n grad += (reg * (np.outer(Lx[i] - Lx[j], X[i] - X[j]) -\n np.outer(Lx[i] - Lx[l], X[i] - X[l])))\n grad = 2 * grad\n return grad, loss, total_active\n\n # we check that the gradient we have computed in the non-performant implem\n # is indeed the true gradient on a toy example:\n\n def _select_targets(X, y, k):\n target_neighbors = np.empty((X.shape[0], k), dtype=int)\n for label in np.unique(y):\n inds, = np.nonzero(y == label)\n dd = euclidean_distances(X[inds], squared=True)\n np.fill_diagonal(dd, np.inf)\n nn = np.argsort(dd)[..., :k]\n target_neighbors[inds] = inds[nn]\n return target_neighbors\n\n target_neighbors = _select_targets(X, y, 2)\n regularization = 0.5\n n_features = X.shape[1]\n x0 = np.random.randn(1, n_features)\n\n def loss(x0):\n return loss_fn(x0.reshape(-1, X.shape[1]), X, y, target_neighbors,\n regularization)[1]\n\n def grad(x0):\n return loss_fn(x0.reshape(-1, X.shape[1]), X, y, target_neighbors,\n regularization)[0].ravel()\n\n scipy.optimize.check_grad(loss, grad, x0.ravel())\n\n class LMNN_with_callback(LMNN):\n \"\"\" We will use a callback to get the gradient (see later)\n \"\"\"\n\n def __init__(self, callback, *args, **kwargs):\n self.callback = callback\n super(LMNN_with_callback, self).__init__(*args, **kwargs)\n\n def _loss_grad(self, *args, **kwargs):\n grad, objective, total_active = (\n super(LMNN_with_callback, self)._loss_grad(*args, **kwargs))\n self.callback.append(grad)\n return grad, objective, total_active\n\n class LMNN_nonperformant(LMNN_with_callback):\n\n def fit(self, X, y):\n self.y = y\n return super(LMNN_nonperformant, self).fit(X, y)\n\n def _loss_grad(self, X, L, dfG, k, reg, target_neighbors, label_inds):\n grad, loss, total_active = loss_fn(L.ravel(), X, self.y,\n target_neighbors, self.regularization)\n self.callback.append(grad)\n return grad, loss, total_active\n\n mem1, mem2 = [], []\n lmnn_perf = LMNN_with_callback(verbose=True, random_state=42,\n init='identity', max_iter=30, callback=mem1)\n lmnn_nonperf = LMNN_nonperformant(verbose=True, random_state=42,\n init='identity', max_iter=30,\n callback=mem2)\n objectives, obj_diffs, learn_rate, total_active = (dict(), dict(), dict(),\n dict())\n for algo, name in zip([lmnn_perf, lmnn_nonperf], ['perf', 'nonperf']):\n algo.fit(X, y)\n out, _ = capsys.readouterr()\n lines = re.split(\"\\n+\", out)\n # we get every variable that is printed from the algorithm in verbose\n num = r'(-?\\d+.?\\d*(e[+|-]\\d+)?)'\n strings = [re.search(r\"\\d+ (?:{}) (?:{}) (?:(\\d+)) (?:{})\"\n .format(num, num, num), s) for s in lines]\n objectives[name] = [float(match.group(1)) for match in strings if match is\n not None]\n obj_diffs[name] = [float(match.group(3)) for match in strings if match is\n not None]\n total_active[name] = [float(match.group(5)) for match in strings if\n match is not\n None]\n learn_rate[name] = [float(match.group(6)) for match in strings if match is\n not None]\n assert len(strings) >= 10 # we ensure that we actually did more than 10\n # iterations\n assert total_active[name][0] >= 2 # we ensure that we have some active\n # constraints (that's the case we want to test)\n # we remove the last element because it can be equal to the penultimate\n # if the last gradient update is null\n for i in range(len(mem1)):\n np.testing.assert_allclose(lmnn_perf.callback[i],\n lmnn_nonperf.callback[i],\n err_msg='Gradient different at position '\n '{}'.format(i))\n np.testing.assert_allclose(objectives['perf'], objectives['nonperf'])\n np.testing.assert_allclose(obj_diffs['perf'], obj_diffs['nonperf'])\n np.testing.assert_allclose(total_active['perf'], total_active['nonperf'])\n np.testing.assert_allclose(learn_rate['perf'], learn_rate['nonperf'])\n\n\[email protected]('X, y, loss', [(np.array([[0], [1], [2], [3]]),\n [1, 1, 0, 0], 3.0),\n (np.array([[0], [1], [2], [3]]),\n [1, 0, 0, 1], 26.)])\ndef test_toy_ex_lmnn(X, y, loss):\n \"\"\"Test that the loss give the right result on a toy example\"\"\"\n L = np.array([[1]])\n lmnn = LMNN(k=1, regularization=0.5)\n\n k = lmnn.k\n reg = lmnn.regularization\n\n X, y = lmnn._prepare_inputs(X, y, dtype=float,\n ensure_min_samples=2)\n num_pts, n_components = X.shape\n unique_labels, label_inds = np.unique(y, return_inverse=True)\n lmnn.labels_ = np.arange(len(unique_labels))\n lmnn.components_ = np.eye(n_components)\n\n target_neighbors = lmnn._select_targets(X, label_inds)\n\n # sum outer products\n dfG = _sum_outer_products(X, target_neighbors.flatten(),\n np.repeat(np.arange(X.shape[0]), k))\n\n # storage\n a1 = [None] * k\n a2 = [None] * k\n for nn_idx in xrange(k):\n a1[nn_idx] = np.array([])\n a2[nn_idx] = np.array([])\n\n # assert that the loss equals the one computed by hand\n assert lmnn._loss_grad(X, L.reshape(-1, X.shape[1]), dfG, k,\n reg, target_neighbors, label_inds)[1] == loss\n\n\ndef test_convergence_simple_example(capsys):\n # LMNN should converge on this simple example, which it did not with\n # this issue: https://github.com/scikit-learn-contrib/metric-learn/issues/88\n X, y = make_classification(random_state=0)\n lmnn = LMNN(verbose=True)\n lmnn.fit(X, y)\n out, _ = capsys.readouterr()\n assert \"LMNN converged with objective\" in out\n\n\ndef test_no_twice_same_objective(capsys):\n # test that the objective function never has twice the same value\n # see https://github.com/scikit-learn-contrib/metric-learn/issues/88\n X, y = make_classification(random_state=0)\n lmnn = LMNN(verbose=True)\n lmnn.fit(X, y)\n out, _ = capsys.readouterr()\n lines = re.split(\"\\n+\", out)\n # we get only objectives from each line:\n # the regexp matches a float that follows an integer (the iteration\n # number), and which is followed by a (signed) float (delta obj). It\n # matches for instance:\n # 3 **1113.7665747189938** -3.182774197440267 46431.0200999999999998e-06\n objectives = [re.search(r\"\\d* (?:(\\d*.\\d*))[ | -]\\d*.\\d*\", s)\n for s in lines]\n objectives = [match.group(1) for match in objectives if match is not None]\n # we remove the last element because it can be equal to the penultimate\n # if the last gradient update is null\n assert len(objectives[:-1]) == len(set(objectives[:-1]))\n\n\nclass TestSDML(MetricTestCase):\n\n @pytest.mark.skipif(HAS_SKGGM,\n reason=\"The warning can be thrown only if skggm is \"\n \"not installed.\")\n def test_sdml_supervised_raises_warning_msg_not_installed_skggm(self):\n \"\"\"Tests that the right warning message is raised if someone tries to\n use SDML_Supervised but has not installed skggm, and that the algorithm\n fails to converge\"\"\"\n # TODO: remove if we don't need skggm anymore\n # load_iris: dataset where we know scikit-learn's graphical lasso fails\n # with a Floating Point error\n X, y = load_iris(return_X_y=True)\n sdml_supervised = SDML_Supervised(balance_param=0.5, use_cov=True,\n sparsity_param=0.01)\n msg = (\"There was a problem in SDML when using scikit-learn's graphical \"\n \"lasso solver. skggm's graphical lasso can sometimes converge on \"\n \"non SPD cases where scikit-learn's graphical lasso fails to \"\n \"converge. Try to install skggm and rerun the algorithm (see \"\n \"the README.md for the right version of skggm). The following \"\n \"error message was thrown:\")\n with pytest.raises(RuntimeError) as raised_error:\n sdml_supervised.fit(X, y)\n assert str(raised_error.value).startswith(msg)\n\n @pytest.mark.skipif(HAS_SKGGM,\n reason=\"The warning can be thrown only if skggm is \"\n \"not installed.\")\n def test_sdml_raises_warning_msg_not_installed_skggm(self):\n \"\"\"Tests that the right warning message is raised if someone tries to\n use SDML but has not installed skggm, and that the algorithm fails to\n converge\"\"\"\n # TODO: remove if we don't need skggm anymore\n # case on which we know that scikit-learn's graphical lasso fails\n # because it will return a non SPD matrix\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n sdml = SDML(prior='identity', balance_param=100, verbose=True)\n\n msg = (\"There was a problem in SDML when using scikit-learn's graphical \"\n \"lasso solver. skggm's graphical lasso can sometimes converge on \"\n \"non SPD cases where scikit-learn's graphical lasso fails to \"\n \"converge. Try to install skggm and rerun the algorithm (see \"\n \"the README.md for the right version of skggm).\")\n with pytest.raises(RuntimeError) as raised_error:\n sdml.fit(pairs, y_pairs)\n assert msg == str(raised_error.value)\n\n @pytest.mark.skipif(not HAS_SKGGM,\n reason=\"The warning can be thrown only if skggm is \"\n \"installed.\")\n def test_sdml_raises_warning_msg_installed_skggm(self):\n \"\"\"Tests that the right warning message is raised if someone tries to\n use SDML and has installed skggm, and that the algorithm fails to\n converge\"\"\"\n # TODO: remove if we don't need skggm anymore\n # case on which we know that skggm's graphical lasso fails\n # because it will return non finite values\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n sdml = SDML(prior='identity', balance_param=100, verbose=True)\n\n msg = (\"There was a problem in SDML when using skggm's graphical \"\n \"lasso solver.\")\n with pytest.raises(RuntimeError) as raised_error:\n sdml.fit(pairs, y_pairs)\n assert msg == str(raised_error.value)\n\n @pytest.mark.skipif(not HAS_SKGGM,\n reason=\"The warning can be thrown only if skggm is \"\n \"installed.\")\n def test_sdml_supervised_raises_warning_msg_installed_skggm(self):\n \"\"\"Tests that the right warning message is raised if someone tries to\n use SDML_Supervised but has not installed skggm, and that the algorithm\n fails to converge\"\"\"\n # TODO: remove if we don't need skggm anymore\n # case on which we know that skggm's graphical lasso fails\n # because it will return non finite values\n rng = np.random.RandomState(42)\n # This example will create a diagonal em_cov with a negative coeff (\n # pathological case)\n X = np.array([[-10., 0.], [10., 0.], [5., 0.], [3., 0.]])\n y = [0, 0, 1, 1]\n sdml_supervised = SDML_Supervised(balance_param=0.5, prior='identity',\n sparsity_param=0.01, random_state=rng)\n msg = (\"There was a problem in SDML when using skggm's graphical \"\n \"lasso solver.\")\n with pytest.raises(RuntimeError) as raised_error:\n sdml_supervised.fit(X, y)\n assert msg == str(raised_error.value)\n\n @pytest.mark.skipif(not HAS_SKGGM,\n reason=\"It's only in the case where skggm is installed\"\n \"that no warning should be thrown.\")\n def test_raises_no_warning_installed_skggm(self):\n # otherwise we should be able to instantiate and fit SDML and it\n # should raise no error and no ConvergenceWarning\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., -55.], [0., -60]]])\n y_pairs = [1, -1]\n X, y = make_classification(random_state=42)\n with pytest.warns(None) as records:\n sdml = SDML(prior='covariance')\n sdml.fit(pairs, y_pairs)\n for record in records:\n assert record.category is not ConvergenceWarning\n with pytest.warns(None) as records:\n sdml_supervised = SDML_Supervised(prior='identity', balance_param=1e-5)\n sdml_supervised.fit(X, y)\n for record in records:\n assert record.category is not ConvergenceWarning\n\n def test_iris(self):\n # Note: this is a flaky test, which fails for certain seeds.\n # TODO: un-flake it!\n rs = np.random.RandomState(5555)\n\n sdml = SDML_Supervised(num_constraints=1500, prior='identity',\n balance_param=5e-5)\n sdml.fit(self.iris_points, self.iris_labels, random_state=rs)\n csep = class_separation(sdml.transform(self.iris_points),\n self.iris_labels)\n self.assertLess(csep, 0.22)\n\n def test_deprecation_num_labeled(self):\n # test that a deprecation message is thrown if num_labeled is set at\n # initialization\n # TODO: remove in v.0.6\n X, y = make_classification(random_state=42)\n sdml_supervised = SDML_Supervised(num_labeled=np.inf, prior='identity',\n balance_param=5e-5)\n msg = ('\"num_labeled\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0')\n assert_warns_message(DeprecationWarning, msg, sdml_supervised.fit, X, y)\n\n def test_sdml_raises_warning_non_psd(self):\n \"\"\"Tests that SDML raises a warning on a toy example where we know the\n pseudo-covariance matrix is not PSD\"\"\"\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y = [1, -1]\n sdml = SDML(prior='covariance', sparsity_param=0.01, balance_param=0.5)\n msg = (\"Warning, the input matrix of graphical lasso is not \"\n \"positive semi-definite (PSD). The algorithm may diverge, \"\n \"and lead to degenerate solutions. \"\n \"To prevent that, try to decrease the balance parameter \"\n \"`balance_param` and/or to set prior='identity'.\")\n with pytest.warns(ConvergenceWarning) as raised_warning:\n try:\n sdml.fit(pairs, y)\n except Exception:\n pass\n # we assert that this warning is in one of the warning raised by the\n # estimator\n assert msg in list(map(lambda w: str(w.message), raised_warning))\n\n def test_sdml_converges_if_psd(self):\n \"\"\"Tests that sdml converges on a simple problem where we know the\n pseudo-covariance matrix is PSD\"\"\"\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., -55.], [0., -60]]])\n y = [1, -1]\n sdml = SDML(prior='covariance', sparsity_param=0.01, balance_param=0.5)\n sdml.fit(pairs, y)\n assert np.isfinite(sdml.get_mahalanobis_matrix()).all()\n\n @pytest.mark.skipif(not HAS_SKGGM,\n reason=\"sklearn's graphical_lasso can sometimes not \"\n \"work on some non SPD problems. We test that \"\n \"is works only if skggm is installed.\")\n def test_sdml_works_on_non_spd_pb_with_skggm(self):\n \"\"\"Test that SDML works on a certain non SPD problem on which we know\n it should work, but scikit-learn's graphical_lasso does not work\"\"\"\n X, y = load_iris(return_X_y=True)\n sdml = SDML_Supervised(balance_param=0.5, sparsity_param=0.01,\n prior='covariance',\n random_state=np.random.RandomState(42))\n sdml.fit(X, y)\n\n def test_deprecation_use_cov(self):\n # test that a deprecation message is thrown if use_cov is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n sdml_supervised = SDML_Supervised(use_cov=np.ones_like(X),\n balance_param=1e-5)\n msg = ('\"use_cov\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n 'removed in 0.6.0. Use \"prior\" instead.')\n with pytest.warns(DeprecationWarning) as raised_warning:\n sdml_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n sdml = SDML(use_cov=np.ones_like(X), balance_param=1e-5)\n with pytest.warns(DeprecationWarning) as raised_warning:\n sdml.fit(pairs, y_pairs)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning(self):\n # test that a ChangedBehavior warning is thrown about the init, if the\n # default parameters are used (except for the balance_param that we need\n # to set for the algorithm to not diverge)\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n sdml_supervised = SDML_Supervised(balance_param=1e-5)\n msg = (\"Warning, no prior was set (`prior=None`). As of version 0.5.0, \"\n \"the default prior will now be set to \"\n \"'identity', instead of 'covariance'. If you still want to use \"\n \"the inverse of the covariance matrix as a prior, \"\n \"set prior='covariance'. This warning will disappear in \"\n \"v0.6.0, and `prior` parameter's default value will be set to \"\n \"'identity'.\")\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n sdml_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n sdml = SDML(balance_param=1e-5)\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n sdml.fit(pairs, y_pairs)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_deprecation_random_state(self):\n # test that a deprecation message is thrown if random_state is set at\n # fit time\n # TODO: remove in v.0.6\n X, y = load_iris(return_X_y=True)\n sdml_supervised = SDML_Supervised(balance_param=5e-5)\n msg = ('\"random_state\" parameter in the `fit` function is '\n 'deprecated. Set `random_state` at initialization '\n 'instead (when instantiating a new `SDML_Supervised` '\n 'object).')\n with pytest.warns(DeprecationWarning) as raised_warning:\n sdml_supervised.fit(X, y, random_state=np.random)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning_random_state(self):\n # test that a ChangedBehavior warning is thrown if the random_state is\n # not set in fit.\n # TODO: remove in v.0.6\n X, y = load_iris(return_X_y=True)\n sdml_supervised = SDML_Supervised(balance_param=5e-5)\n msg = ('As of v0.5.0, `SDML_Supervised` now uses the '\n '`random_state` given at initialization to sample '\n 'constraints, not the default `np.random` from the `fit` '\n 'method, since this argument is now deprecated. '\n 'This warning will disappear in v0.6.0.')\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n sdml_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n\[email protected](not HAS_SKGGM,\n reason='The message should be printed only if skggm is '\n 'installed.')\ndef test_verbose_has_installed_skggm_sdml(capsys):\n # Test that if users have installed skggm, a message is printed telling them\n # skggm's solver is used (when they use SDML)\n # TODO: remove if we don't need skggm anymore\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., -55.], [0., -60]]])\n y_pairs = [1, -1]\n sdml = SDML(verbose=True, prior='covariance')\n sdml.fit(pairs, y_pairs)\n out, _ = capsys.readouterr()\n assert \"SDML will use skggm's graphical lasso solver.\" in out\n\n\[email protected](not HAS_SKGGM,\n reason='The message should be printed only if skggm is '\n 'installed.')\ndef test_verbose_has_installed_skggm_sdml_supervised(capsys):\n # Test that if users have installed skggm, a message is printed telling them\n # skggm's solver is used (when they use SDML_Supervised)\n # TODO: remove if we don't need skggm anymore\n X, y = load_iris(return_X_y=True)\n sdml = SDML_Supervised(verbose=True, prior='identity', balance_param=1e-5)\n sdml.fit(X, y)\n out, _ = capsys.readouterr()\n assert \"SDML will use skggm's graphical lasso solver.\" in out\n\n\[email protected](HAS_SKGGM,\n reason='The message should be printed only if skggm is '\n 'not installed.')\ndef test_verbose_has_not_installed_skggm_sdml(capsys):\n # Test that if users have installed skggm, a message is printed telling them\n # skggm's solver is used (when they use SDML)\n # TODO: remove if we don't need skggm anymore\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., -55.], [0., -60]]])\n y_pairs = [1, -1]\n sdml = SDML(verbose=True, prior='covariance')\n sdml.fit(pairs, y_pairs)\n out, _ = capsys.readouterr()\n assert \"SDML will use scikit-learn's graphical lasso solver.\" in out\n\n\[email protected](HAS_SKGGM,\n reason='The message should be printed only if skggm is '\n 'not installed.')\ndef test_verbose_has_not_installed_skggm_sdml_supervised(capsys):\n # Test that if users have installed skggm, a message is printed telling them\n # skggm's solver is used (when they use SDML_Supervised)\n # TODO: remove if we don't need skggm anymore\n X, y = make_classification(random_state=42)\n sdml = SDML_Supervised(verbose=True, balance_param=1e-5, prior='identity')\n sdml.fit(X, y)\n out, _ = capsys.readouterr()\n assert \"SDML will use scikit-learn's graphical lasso solver.\" in out\n\n\nclass TestNCA(MetricTestCase):\n def test_iris(self):\n n = self.iris_points.shape[0]\n\n # Without dimension reduction\n nca = NCA(max_iter=(100000 // n))\n nca.fit(self.iris_points, self.iris_labels)\n csep = class_separation(nca.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.15)\n\n # With dimension reduction\n nca = NCA(max_iter=(100000 // n), n_components=2)\n nca.fit(self.iris_points, self.iris_labels)\n csep = class_separation(nca.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.20)\n\n def test_finite_differences(self):\n \"\"\"Test gradient of loss function\n\n Assert that the gradient is almost equal to its finite differences\n approximation.\n \"\"\"\n # Initialize the transformation `M`, as well as `X` and `y` and `NCA`\n X, y = make_classification()\n M = np.random.randn(np.random.randint(1, X.shape[1] + 1), X.shape[1])\n mask = y[:, np.newaxis] == y[np.newaxis, :]\n nca = NCA()\n nca.n_iter_ = 0\n\n def fun(M):\n return nca._loss_grad_lbfgs(M, X, mask)[0]\n\n def grad(M):\n return nca._loss_grad_lbfgs(M, X, mask)[1].ravel()\n\n # compute relative error\n epsilon = np.sqrt(np.finfo(float).eps)\n rel_diff = (check_grad(fun, grad, M.ravel()) /\n np.linalg.norm(approx_fprime(M.ravel(), fun, epsilon)))\n np.testing.assert_almost_equal(rel_diff, 0., decimal=6)\n\n def test_simple_example(self):\n \"\"\"Test on a simple example.\n\n Puts four points in the input space where the opposite labels points are\n next to each other. After transform the same labels points should be next\n to each other.\n\n \"\"\"\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n nca = NCA(n_components=2,)\n nca.fit(X, y)\n Xansformed = nca.transform(X)\n np.testing.assert_equal(pairwise_distances(Xansformed).argsort()[:, 1],\n np.array([2, 3, 0, 1]))\n\n def test_singleton_class(self):\n X = self.iris_points\n y = self.iris_labels\n\n # one singleton class: test fitting works\n singleton_class = 1\n ind_singleton, = np.where(y == singleton_class)\n y[ind_singleton] = 2\n y[ind_singleton[0]] = singleton_class\n\n nca = NCA(max_iter=30)\n nca.fit(X, y)\n\n # One non-singleton class: test fitting works\n ind_1, = np.where(y == 1)\n ind_2, = np.where(y == 2)\n y[ind_1] = 0\n y[ind_1[0]] = 1\n y[ind_2] = 0\n y[ind_2[0]] = 2\n\n nca = NCA(max_iter=30)\n nca.fit(X, y)\n\n # Only singleton classes: test fitting does nothing (the gradient\n # must be null in this case, so the final matrix must stay like\n # the initialization)\n ind_0, = np.where(y == 0)\n ind_1, = np.where(y == 1)\n ind_2, = np.where(y == 2)\n X = X[[ind_0[0], ind_1[0], ind_2[0]]]\n y = y[[ind_0[0], ind_1[0], ind_2[0]]]\n\n A = make_spd_matrix(X.shape[1], X.shape[1])\n nca = NCA(init=A, max_iter=30, n_components=X.shape[1])\n nca.fit(X, y)\n assert_array_equal(nca.components_, A)\n\n def test_one_class(self):\n # if there is only one class the gradient is null, so the final matrix\n # must stay like the initialization\n X = self.iris_points[self.iris_labels == 0]\n y = self.iris_labels[self.iris_labels == 0]\n\n A = make_spd_matrix(X.shape[1], X.shape[1])\n nca = NCA(init=A, max_iter=30, n_components=X.shape[1])\n nca.fit(X, y)\n assert_array_equal(nca.components_, A)\n\n def test_changed_behaviour_warning(self):\n # test that a ChangedBehavior warning is thrown about the init, if the\n # default parameters are used.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n nca = NCA()\n msg = (\"Warning, no init was set (`init=None`). As of version 0.5.0, \"\n \"the default init will now be set to 'auto', instead of the \"\n \"previous scaling matrix. If you still want to use the same \"\n \"scaling matrix as before, set \"\n \"init=np.eye(X.shape[1])/(np.maximum(X.max(axis=0)-X.min(axis=0)\"\n \", EPS))). This warning will disappear in v0.6.0, and `init` \"\n \"parameter's default value will be set to 'auto'.\")\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n nca.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n\[email protected]('num_dims', [None, 2])\ndef test_deprecation_num_dims_nca(num_dims):\n # test that a deprecation message is thrown if num_dims is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n nca = NCA(num_dims=num_dims)\n msg = ('\"num_dims\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0. Use \"n_components\" instead')\n with pytest.warns(DeprecationWarning) as raised_warning:\n nca.fit(X, y)\n assert (str(raised_warning[0].message) == msg)\n\n\nclass TestLFDA(MetricTestCase):\n def test_iris(self):\n lfda = LFDA(k=2, n_components=2)\n lfda.fit(self.iris_points, self.iris_labels)\n csep = class_separation(lfda.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.15)\n\n # Sanity checks for learned matrices.\n self.assertEqual(lfda.get_mahalanobis_matrix().shape, (4, 4))\n self.assertEqual(lfda.components_.shape, (2, 4))\n\n\[email protected]('num_dims', [None, 2])\ndef test_deprecation_num_dims_lfda(num_dims):\n # test that a deprecation message is thrown if num_dims is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n lfda = LFDA(num_dims=num_dims)\n msg = ('\"num_dims\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0. Use \"n_components\" instead')\n with pytest.warns(DeprecationWarning) as raised_warning:\n lfda.fit(X, y)\n assert (str(raised_warning[0].message) == msg)\n\n\nclass TestRCA(MetricTestCase):\n def test_iris(self):\n rca = RCA_Supervised(n_components=2, num_chunks=30, chunk_size=2)\n rca.fit(self.iris_points, self.iris_labels)\n csep = class_separation(rca.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.29)\n\n def test_deprecation_pca_comps(self):\n # test that a deprecation message is thrown if pca_comps is set at\n # initialization\n # TODO: remove in v.0.6\n X, y = make_classification(random_state=42, n_samples=100)\n rca_supervised = RCA_Supervised(pca_comps=X.shape[1], num_chunks=20)\n msg = ('\"pca_comps\" parameter is not used. '\n 'It has been deprecated in version 0.5.0 and will be'\n 'removed in 0.6.0. RCA will not do PCA preprocessing anymore. If '\n 'you still want to do it, you could use '\n '`sklearn.decomposition.PCA` and an `sklearn.pipeline.Pipeline`.')\n with pytest.warns(ChangedBehaviorWarning) as expected_msg:\n rca_supervised.fit(X, y)\n assert any(str(w.message) == msg for w in expected_msg)\n\n rca = RCA(pca_comps=X.shape[1])\n with pytest.warns(ChangedBehaviorWarning) as expected_msg:\n rca.fit(X, y)\n assert any(str(w.message) == msg for w in expected_msg)\n\n def test_changedbehaviorwarning_preprocessing(self):\n # test that a ChangedBehaviorWarning is thrown when using RCA\n # TODO: remove in v.0.6\n\n msg = (\"RCA will no longer center the data before training. If you want \"\n \"to do some preprocessing, you should do it manually (you can also \"\n \"use an `sklearn.pipeline.Pipeline` for instance). This warning \"\n \"will disappear in version 0.6.0.\")\n\n X, y = make_classification(random_state=42, n_samples=100)\n rca_supervised = RCA_Supervised(num_chunks=20)\n with pytest.warns(ChangedBehaviorWarning) as expected_msg:\n rca_supervised.fit(X, y)\n assert any(str(w.message) == msg for w in expected_msg)\n\n rca = RCA()\n with pytest.warns(ChangedBehaviorWarning) as expected_msg:\n rca.fit(X, y)\n assert any(str(w.message) == msg for w in expected_msg)\n\n def test_rank_deficient_returns_warning(self):\n \"\"\"Checks that if the covariance matrix is not invertible, we raise a\n warning message advising to use PCA\"\"\"\n X, y = load_iris(return_X_y=True)\n # we make the fourth column a linear combination of the two first,\n # so that the covariance matrix will not be invertible:\n X[:, 3] = X[:, 0] + 3 * X[:, 1]\n rca = RCA()\n msg = ('The inner covariance matrix is not invertible, '\n 'so the transformation matrix may contain Nan values. '\n 'You should reduce the dimensionality of your input,'\n 'for instance using `sklearn.decomposition.PCA` as a '\n 'preprocessing step.')\n with pytest.warns(None) as raised_warnings:\n rca.fit(X, y)\n assert any(str(w.message) == msg for w in raised_warnings)\n\n def test_deprecation_random_state(self):\n # test that a deprecation message is thrown if random_state is set at\n # fit time\n # TODO: remove in v.0.6\n X, y = make_classification(random_state=42, n_samples=100)\n rca_supervised = RCA_Supervised(num_chunks=20)\n msg = ('\"random_state\" parameter in the `fit` function is '\n 'deprecated. Set `random_state` at initialization '\n 'instead (when instantiating a new `RCA_Supervised` '\n 'object).')\n with pytest.warns(DeprecationWarning) as raised_warning:\n rca_supervised.fit(X, y, random_state=np.random)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning_random_state(self):\n # test that a ChangedBehavior warning is thrown if the random_state is\n # not set in fit.\n # TODO: remove in v.0.6\n X, y = make_classification(random_state=42, n_samples=100)\n rca_supervised = RCA_Supervised(num_chunks=20)\n msg = ('As of v0.5.0, `RCA_Supervised` now uses the '\n '`random_state` given at initialization to sample '\n 'constraints, not the default `np.random` from the `fit` '\n 'method, since this argument is now deprecated. '\n 'This warning will disappear in v0.6.0.')\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n rca_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n\[email protected]('num_dims', [None, 2])\ndef test_deprecation_num_dims_rca(num_dims):\n # test that a deprecation message is thrown if num_dims is set at\n # initialization\n # TODO: remove in v.0.6\n X, y = load_iris(return_X_y=True)\n rca = RCA(num_dims=num_dims)\n msg = ('\"num_dims\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0. Use \"n_components\" instead')\n with pytest.warns(DeprecationWarning) as raised_warning:\n rca.fit(X, y)\n assert any(str(w.message) == msg for w in raised_warning)\n\n # we take a small number of chunks so that RCA works on iris\n rca_supervised = RCA_Supervised(num_dims=num_dims, num_chunks=10)\n msg = ('\"num_dims\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0. Use \"n_components\" instead')\n with pytest.warns(DeprecationWarning) as raised_warning:\n rca_supervised.fit(X, y)\n assert any(str(w.message) == msg for w in raised_warning)\n\n\nclass TestMLKR(MetricTestCase):\n def test_iris(self):\n mlkr = MLKR()\n mlkr.fit(self.iris_points, self.iris_labels)\n csep = class_separation(mlkr.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.25)\n\n def test_finite_differences(self):\n \"\"\"Test gradient of loss function\n\n Assert that the gradient is almost equal to its finite differences\n approximation.\n \"\"\"\n # Initialize the transformation `M`, as well as `X`, and `y` and `MLKR`\n X, y = make_regression(n_features=4, random_state=1, n_samples=20)\n X, y = check_X_y(X, y)\n M = np.random.randn(2, X.shape[1])\n mlkr = MLKR()\n mlkr.n_iter_ = 0\n\n def fun(M):\n return mlkr._loss(M, X, y)[0]\n\n def grad_fn(M):\n return mlkr._loss(M, X, y)[1].ravel()\n\n # compute relative error\n rel_diff = check_grad(fun, grad_fn, M.ravel()) / np.linalg.norm(grad_fn(M))\n np.testing.assert_almost_equal(rel_diff, 0.)\n\n def test_deprecation_A0(self):\n # test that a deprecation message is thrown if A0 is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n mlkr = MLKR(A0=np.ones_like(X))\n msg = ('\"A0\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n 'removed in 0.6.0. Use \"init\" instead.')\n with pytest.warns(DeprecationWarning) as raised_warning:\n mlkr.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning(self):\n # test that a ChangedBehavior warning is thrown about the init, if the\n # default parameters are used.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([0.1, 0.2, 0.3, 0.4])\n mlkr = MLKR()\n msg = (\"Warning, no init was set (`init=None`). As of version 0.5.0, \"\n \"the default init will now be set to 'auto', instead of 'pca'. \"\n \"If you still want to use PCA as an init, set init='pca'. \"\n \"This warning will disappear in v0.6.0, and `init` parameter's\"\n \" default value will be set to 'auto'.\")\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n mlkr.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n\[email protected]('num_dims', [None, 2])\ndef test_deprecation_num_dims_mlkr(num_dims):\n # test that a deprecation message is thrown if num_dims is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n mlkr = MLKR(num_dims=num_dims)\n msg = ('\"num_dims\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0. Use \"n_components\" instead')\n with pytest.warns(DeprecationWarning) as raised_warning:\n mlkr.fit(X, y)\n assert (str(raised_warning[0].message) == msg)\n\n\nclass TestMMC(MetricTestCase):\n def test_iris(self):\n\n # Generate full set of constraints for comparison with reference\n # implementation\n mask = self.iris_labels[None] == self.iris_labels[:, None]\n a, b = np.nonzero(np.triu(mask, k=1))\n c, d = np.nonzero(np.triu(~mask, k=1))\n\n # Full metric\n n_features = self.iris_points.shape[1]\n mmc = MMC(convergence_threshold=0.01, init=np.eye(n_features) / 10)\n mmc.fit(*wrap_pairs(self.iris_points, [a, b, c, d]))\n expected = [[+0.000514, +0.000868, -0.001195, -0.001703],\n [+0.000868, +0.001468, -0.002021, -0.002879],\n [-0.001195, -0.002021, +0.002782, +0.003964],\n [-0.001703, -0.002879, +0.003964, +0.005648]]\n assert_array_almost_equal(expected, mmc.get_mahalanobis_matrix(),\n decimal=6)\n\n # Diagonal metric\n mmc = MMC(diagonal=True)\n mmc.fit(*wrap_pairs(self.iris_points, [a, b, c, d]))\n expected = [0, 0, 1.210220, 1.228596]\n assert_array_almost_equal(np.diag(expected), mmc.get_mahalanobis_matrix(),\n decimal=6)\n\n # Supervised Full\n mmc = MMC_Supervised()\n mmc.fit(self.iris_points, self.iris_labels)\n csep = class_separation(mmc.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.15)\n\n # Supervised Diagonal\n mmc = MMC_Supervised(diagonal=True)\n mmc.fit(self.iris_points, self.iris_labels)\n csep = class_separation(mmc.transform(self.iris_points), self.iris_labels)\n self.assertLess(csep, 0.2)\n\n def test_deprecation_num_labeled(self):\n # test that a deprecation message is thrown if num_labeled is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n mmc_supervised = MMC_Supervised(num_labeled=np.inf)\n msg = ('\"num_labeled\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0')\n assert_warns_message(DeprecationWarning, msg, mmc_supervised.fit, X, y)\n\n def test_deprecation_A0(self):\n # test that a deprecation message is thrown if A0 is set at\n # initialization\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n mmc_supervised = MMC_Supervised(A0=np.ones_like(X))\n msg = ('\"A0\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n 'removed in 0.6.0. Use \"init\" instead.')\n with pytest.warns(DeprecationWarning) as raised_warning:\n mmc_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n mmc = MMC(A0=np.ones_like(X))\n with pytest.warns(DeprecationWarning) as raised_warning:\n mmc.fit(pairs, y_pairs)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning(self):\n # test that a ChangedBehavior warning is thrown about the init, if the\n # default parameters are used.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n mmc_supervised = MMC_Supervised()\n msg = (\"Warning, no init was set (`init=None`). As of version 0.5.0, \"\n \"the default init will now be set to 'identity', instead of the \"\n \"identity divided by a scaling factor of 10. \"\n \"If you still want to use the same init as in previous \"\n \"versions, set init=np.eye(d)/10, where d is the dimension \"\n \"of your input space (d=pairs.shape[1]). \"\n \"This warning will disappear in v0.6.0, and `init` parameter's\"\n \" default value will be set to 'auto'.\")\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n mmc_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n pairs = np.array([[[-10., 0.], [10., 0.]], [[0., 50.], [0., -60]]])\n y_pairs = [1, -1]\n mmc = MMC()\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n mmc.fit(pairs, y_pairs)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_deprecation_random_state(self):\n # test that a deprecation message is thrown if random_state is set at\n # fit time\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n mmc_supervised = MMC_Supervised()\n msg = ('\"random_state\" parameter in the `fit` function is '\n 'deprecated. Set `random_state` at initialization '\n 'instead (when instantiating a new `MMC_Supervised` '\n 'object).')\n with pytest.warns(DeprecationWarning) as raised_warning:\n mmc_supervised.fit(X, y, random_state=np.random)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n def test_changed_behaviour_warning_random_state(self):\n # test that a ChangedBehavior warning is thrown if the random_state is\n # not set in fit.\n # TODO: remove in v.0.6\n X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])\n y = np.array([1, 0, 1, 0])\n mmc_supervised = MMC_Supervised()\n msg = ('As of v0.5.0, `MMC_Supervised` now uses the '\n '`random_state` given at initialization to sample '\n 'constraints, not the default `np.random` from the `fit` '\n 'method, since this argument is now deprecated. '\n 'This warning will disappear in v0.6.0.')\n with pytest.warns(ChangedBehaviorWarning) as raised_warning:\n mmc_supervised.fit(X, y)\n assert any(msg == str(wrn.message) for wrn in raised_warning)\n\n\[email protected](('algo_class', 'dataset'),\n [(NCA, make_classification()),\n (MLKR, make_regression())])\ndef test_verbose(algo_class, dataset, capsys):\n # assert there is proper output when verbose = True\n X, y = dataset\n model = algo_class(verbose=True)\n model.fit(X, y)\n out, _ = capsys.readouterr()\n\n # check output\n lines = re.split('\\n+', out)\n header = '{:>10} {:>20} {:>10}'.format('Iteration', 'Objective Value',\n 'Time(s)')\n assert lines[0] == '[{}]'.format(algo_class.__name__)\n assert lines[1] == '[{}] {}'.format(algo_class.__name__, header)\n assert lines[2] == '[{}] {}'.format(algo_class.__name__, '-' * len(header))\n for line in lines[3:-2]:\n # The following regex will match for instance:\n # '[NCA] 0 6.988936e+01 0.01'\n assert re.match(r\"\\[\" + algo_class.__name__ + r\"\\]\\ *\\d+\\ *\\d\\.\\d{6}e[+|-]\"\n r\"\\d+\\ *\\d+\\.\\d{2}\", line)\n assert re.match(r\"\\[\" + algo_class.__name__ + r\"\\] Training took\\ *\"\n r\"\\d+\\.\\d{2}s\\.\", lines[-2])\n assert lines[-1] == ''\n\n\[email protected](('algo_class', 'dataset'),\n [(NCA, make_classification()),\n (MLKR, make_regression(n_features=10))])\ndef test_no_verbose(dataset, algo_class, capsys):\n # assert by default there is no output (verbose=False)\n X, y = dataset\n model = algo_class()\n model.fit(X, y)\n out, _ = capsys.readouterr()\n # check output\n assert (out == '')\n\n\[email protected](('algo_class', 'dataset'),\n [(NCA, make_classification()),\n (MLKR, make_regression(n_features=10))])\ndef test_convergence_warning(dataset, algo_class):\n X, y = dataset\n model = algo_class(max_iter=2, verbose=True)\n cls_name = model.__class__.__name__\n assert_warns_message(ConvergenceWarning,\n '[{}] {} did not converge'.format(cls_name, cls_name),\n model.fit, X, y)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "\"\"\"\nNeighborhood Components Analysis (NCA)\n\"\"\"\n\nfrom __future__ import absolute_import\nimport warnings\nimport time\nimport sys\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.exceptions import ConvergenceWarning, ChangedBehaviorWarning\nfrom sklearn.utils.fixes import logsumexp\nfrom sklearn.base import TransformerMixin\n\nfrom ._util import _initialize_components, _check_n_components\nfrom .base_metric import MahalanobisMixin\n\nEPS = np.finfo(float).eps\n\n\nclass NCA(MahalanobisMixin, TransformerMixin):\n \"\"\"Neighborhood Components Analysis (NCA)\n\n NCA is a distance metric learning algorithm which aims to improve the\n accuracy of nearest neighbors classification compared to the standard\n Euclidean distance. The algorithm directly maximizes a stochastic variant\n of the leave-one-out k-nearest neighbors(KNN) score on the training set.\n It can also learn a low-dimensional linear transformation of data that can\n be used for data visualization and fast classification.\n\n Read more in the :ref:`User Guide <nca>`.\n\n Parameters\n ----------\n init : None, string or numpy array, optional (default=None)\n Initialization of the linear transformation. Possible options are\n 'auto', 'pca', 'identity', 'random', and a numpy array of shape\n (n_features_a, n_features_b). If None, will be set automatically to\n 'auto' (this option is to raise a warning if 'init' is not set,\n and stays to its default value None, in v0.5.0).\n\n 'auto'\n Depending on ``n_components``, the most reasonable initialization\n will be chosen. If ``n_components <= n_classes`` we use 'lda', as\n it uses labels information. If not, but\n ``n_components < min(n_features, n_samples)``, we use 'pca', as\n it projects data in meaningful directions (those of higher\n variance). Otherwise, we just use 'identity'.\n\n 'pca'\n ``n_components`` principal components of the inputs passed\n to :meth:`fit` will be used to initialize the transformation.\n (See `sklearn.decomposition.PCA`)\n\n 'lda'\n ``min(n_components, n_classes)`` most discriminative\n components of the inputs passed to :meth:`fit` will be used to\n initialize the transformation. (If ``n_components > n_classes``,\n the rest of the components will be zero.) (See\n `sklearn.discriminant_analysis.LinearDiscriminantAnalysis`)\n\n 'identity'\n If ``n_components`` is strictly smaller than the\n dimensionality of the inputs passed to :meth:`fit`, the identity\n matrix will be truncated to the first ``n_components`` rows.\n\n 'random'\n The initial transformation will be a random array of shape\n `(n_components, n_features)`. Each value is sampled from the\n standard normal distribution.\n\n numpy array\n n_features_b must match the dimensionality of the inputs passed to\n :meth:`fit` and n_features_a must be less than or equal to that.\n If ``n_components`` is not None, n_features_a must match it.\n\n n_components : int or None, optional (default=None)\n Dimensionality of reduced space (if None, defaults to dimension of X).\n\n num_dims : Not used\n\n .. deprecated:: 0.5.0\n `num_dims` was deprecated in version 0.5.0 and will\n be removed in 0.6.0. Use `n_components` instead.\n\n max_iter : int, optional (default=100)\n Maximum number of iterations done by the optimization algorithm.\n\n tol : float, optional (default=None)\n Convergence tolerance for the optimization.\n\n verbose : bool, optional (default=False)\n Whether to print progress messages or not.\n\n random_state : int or numpy.RandomState or None, optional (default=None)\n A pseudo random number generator object or a seed for it if int. If\n ``init='random'``, ``random_state`` is used to initialize the random\n transformation. If ``init='pca'``, ``random_state`` is passed as an\n argument to PCA when initializing the transformation.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> from metric_learn import NCA\n >>> from sklearn.datasets import load_iris\n >>> iris_data = load_iris()\n >>> X = iris_data['data']\n >>> Y = iris_data['target']\n >>> nca = NCA(max_iter=1000)\n >>> nca.fit(X, Y)\n\n Attributes\n ----------\n n_iter_ : `int`\n The number of iterations the solver has run.\n\n components_ : `numpy.ndarray`, shape=(n_components, n_features)\n The learned linear transformation ``L``.\n\n References\n ----------\n .. [1] J. Goldberger, G. Hinton, S. Roweis, R. Salakhutdinov. `Neighbourhood\n Components Analysis\n <http://www.cs.nyu.edu/~roweis/papers/ncanips.pdf>`_.\n Advances in Neural Information Processing Systems. 17, 513-520, 2005.\n\n .. [2] Wikipedia entry on `Neighborhood Components Analysis\n <https://en.wikipedia.org/wiki/Neighbourhood_components_analysis>`_\n \"\"\"\n\n def __init__(self, init=None, n_components=None, num_dims='deprecated',\n max_iter=100, tol=None, verbose=False, preprocessor=None,\n random_state=None):\n self.n_components = n_components\n self.init = init\n self.num_dims = num_dims\n self.max_iter = max_iter\n self.tol = tol\n self.verbose = verbose\n self.random_state = random_state\n super(NCA, self).__init__(preprocessor)\n\n def fit(self, X, y):\n \"\"\"\n X: data matrix, (n x d)\n y: scalar labels, (n)\n \"\"\"\n if self.num_dims != 'deprecated':\n warnings.warn('\"num_dims\" parameter is not used.'\n ' It has been deprecated in version 0.5.0 and will be'\n ' removed in 0.6.0. Use \"n_components\" instead',\n DeprecationWarning)\n X, labels = self._prepare_inputs(X, y, ensure_min_samples=2)\n n, d = X.shape\n n_components = _check_n_components(d, self.n_components)\n\n # Measure the total training time\n train_time = time.time()\n\n # Initialize A\n # if the init is the default (None), we raise a warning\n if self.init is None:\n # TODO: replace init=None by init='auto' in v0.6.0 and remove the warning\n msg = (\"Warning, no init was set (`init=None`). As of version 0.5.0, \"\n \"the default init will now be set to 'auto', instead of the \"\n \"previous scaling matrix. If you still want to use the same \"\n \"scaling matrix as before, set \"\n \"init=np.eye(X.shape[1])/(np.maximum(X.max(axis=0)-X.min(axis=0)\"\n \", EPS))). This warning will disappear in v0.6.0, and `init` \"\n \"parameter's default value will be set to 'auto'.\")\n warnings.warn(msg, ChangedBehaviorWarning)\n init = 'auto'\n else:\n init = self.init\n A = _initialize_components(n_components, X, labels, init, self.verbose,\n self.random_state)\n\n # Run NCA\n mask = labels[:, np.newaxis] == labels[np.newaxis, :]\n optimizer_params = {'method': 'L-BFGS-B',\n 'fun': self._loss_grad_lbfgs,\n 'args': (X, mask, -1.0),\n 'jac': True,\n 'x0': A.ravel(),\n 'options': dict(maxiter=self.max_iter),\n 'tol': self.tol\n }\n\n # Call the optimizer\n self.n_iter_ = 0\n opt_result = minimize(**optimizer_params)\n\n self.components_ = opt_result.x.reshape(-1, X.shape[1])\n self.n_iter_ = opt_result.nit\n\n # Stop timer\n train_time = time.time() - train_time\n if self.verbose:\n cls_name = self.__class__.__name__\n\n # Warn the user if the algorithm did not converge\n if not opt_result.success:\n warnings.warn('[{}] NCA did not converge: {}'.format(\n cls_name, opt_result.message), ConvergenceWarning)\n\n print('[{}] Training took {:8.2f}s.'.format(cls_name, train_time))\n\n return self\n\n def _loss_grad_lbfgs(self, A, X, mask, sign=1.0):\n\n if self.n_iter_ == 0 and self.verbose:\n header_fields = ['Iteration', 'Objective Value', 'Time(s)']\n header_fmt = '{:>10} {:>20} {:>10}'\n header = header_fmt.format(*header_fields)\n cls_name = self.__class__.__name__\n print('[{cls}]'.format(cls=cls_name))\n print('[{cls}] {header}\\n[{cls}] {sep}'.format(cls=cls_name,\n header=header,\n sep='-' * len(header)))\n\n start_time = time.time()\n\n A = A.reshape(-1, X.shape[1])\n X_embedded = np.dot(X, A.T) # (n_samples, n_components)\n # Compute softmax distances\n p_ij = pairwise_distances(X_embedded, squared=True)\n np.fill_diagonal(p_ij, np.inf)\n p_ij = np.exp(-p_ij - logsumexp(-p_ij, axis=1)[:, np.newaxis])\n # (n_samples, n_samples)\n\n # Compute loss\n masked_p_ij = p_ij * mask\n p = masked_p_ij.sum(axis=1, keepdims=True) # (n_samples, 1)\n loss = p.sum()\n\n # Compute gradient of loss w.r.t. `transform`\n weighted_p_ij = masked_p_ij - p_ij * p\n weighted_p_ij_sym = weighted_p_ij + weighted_p_ij.T\n np.fill_diagonal(weighted_p_ij_sym, - weighted_p_ij.sum(axis=0))\n gradient = 2 * (X_embedded.T.dot(weighted_p_ij_sym)).dot(X)\n\n if self.verbose:\n start_time = time.time() - start_time\n values_fmt = '[{cls}] {n_iter:>10} {loss:>20.6e} {start_time:>10.2f}'\n print(values_fmt.format(cls=self.__class__.__name__,\n n_iter=self.n_iter_, loss=loss,\n start_time=start_time))\n sys.stdout.flush()\n\n self.n_iter_ += 1\n return sign * loss, sign * gradient.ravel()\n" ]
[ [ "numpy.diag", "numpy.dot", "sklearn.datasets.make_classification", "numpy.random.randn", "numpy.zeros_like", "numpy.fill_diagonal", "numpy.where", "sklearn.datasets.make_spd_matrix", "numpy.random.randint", "numpy.ones_like", "numpy.unique", "numpy.arange", "numpy.eye", "sklearn.metrics.euclidean_distances", "numpy.finfo", "sklearn.utils.testing.assert_warns_message", "numpy.testing.assert_almost_equal", "numpy.outer", "numpy.triu", "numpy.nonzero", "sklearn.datasets.load_iris", "numpy.cov", "sklearn.utils.validation.check_X_y", "numpy.testing.assert_allclose", "numpy.argsort", "numpy.array", "numpy.random.RandomState", "numpy.sum", "sklearn.metrics.pairwise_distances", "numpy.random.seed", "numpy.testing.assert_array_equal", "sklearn.datasets.make_regression", "numpy.empty" ], [ "numpy.dot", "sklearn.metrics.pairwise_distances", "sklearn.utils.fixes.logsumexp", "numpy.finfo", "scipy.optimize.minimize", "numpy.fill_diagonal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
WeatherGod/numpy
[ "5be45b280b258e158b93163b937f8f9c08d30393", "5be45b280b258e158b93163b937f8f9c08d30393", "5be45b280b258e158b93163b937f8f9c08d30393", "5be45b280b258e158b93163b937f8f9c08d30393", "5be45b280b258e158b93163b937f8f9c08d30393" ]
[ "numpy/ma/tests/test_regression.py", "numpy/distutils/fcompiler/absoft.py", "numpy/random/__init__.py", "numpy/linalg/setup.py", "numpy/distutils/fcompiler/pg.py" ]
[ "from __future__ import division, absolute_import, print_function\n\nimport numpy as np\nimport numpy.ma as ma\nfrom numpy.testing import *\nfrom numpy.compat import sixu\n\nrlevel = 1\n\nclass TestRegression(TestCase):\n def test_masked_array_create(self,level=rlevel):\n \"\"\"Ticket #17\"\"\"\n x = np.ma.masked_array([0,1,2,3,0,4,5,6],mask=[0,0,0,1,1,1,0,0])\n assert_array_equal(np.ma.nonzero(x),[[1,2,6,7]])\n\n def test_masked_array(self,level=rlevel):\n \"\"\"Ticket #61\"\"\"\n x = np.ma.array(1,mask=[1])\n\n def test_mem_masked_where(self,level=rlevel):\n \"\"\"Ticket #62\"\"\"\n from numpy.ma import masked_where, MaskType\n a = np.zeros((1,1))\n b = np.zeros(a.shape, MaskType)\n c = masked_where(b,a)\n a-c\n\n def test_masked_array_multiply(self,level=rlevel):\n \"\"\"Ticket #254\"\"\"\n a = np.ma.zeros((4,1))\n a[2,0] = np.ma.masked\n b = np.zeros((4,2))\n a*b\n b*a\n\n def test_masked_array_repeat(self, level=rlevel):\n \"\"\"Ticket #271\"\"\"\n np.ma.array([1],mask=False).repeat(10)\n\n def test_masked_array_repr_unicode(self):\n \"\"\"Ticket #1256\"\"\"\n repr(np.ma.array(sixu(\"Unicode\")))\n\n def test_atleast_2d(self):\n \"\"\"Ticket #1559\"\"\"\n a = np.ma.masked_array([0.0, 1.2, 3.5], mask=[False, True, False])\n b = np.atleast_2d(a)\n assert_(a.mask.ndim == 1)\n assert_(b.mask.ndim == 2)\n\n def test_set_fill_value_unicode_py3(self):\n \"\"\"Ticket #2733\"\"\"\n a = np.ma.masked_array(['a', 'b', 'c'], mask=[1, 0, 0])\n a.fill_value = 'X'\n assert_(a.fill_value == 'X')\n\n def test_var_sets_maskedarray_scalar(self):\n \"\"\"Issue gh-2757\"\"\"\n a = np.ma.array(np.arange(5), mask=True)\n mout = np.ma.array(-1, dtype=float)\n a.var(out=mout)\n assert_(mout._data == 0)\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n", "\n# http://www.absoft.com/literature/osxuserguide.pdf\n# http://www.absoft.com/documentation.html\n\n# Notes:\n# - when using -g77 then use -DUNDERSCORE_G77 to compile f2py\n# generated extension modules (works for f2py v2.45.241_1936 and up)\nfrom __future__ import division, absolute_import, print_function\n\nimport os\n\nfrom numpy.distutils.cpuinfo import cpu\nfrom numpy.distutils.fcompiler import FCompiler, dummy_fortran_file\nfrom numpy.distutils.misc_util import cyg2win32\n\ncompilers = ['AbsoftFCompiler']\n\nclass AbsoftFCompiler(FCompiler):\n\n compiler_type = 'absoft'\n description = 'Absoft Corp Fortran Compiler'\n #version_pattern = r'FORTRAN 77 Compiler (?P<version>[^\\s*,]*).*?Absoft Corp'\n version_pattern = r'(f90:.*?(Absoft Pro FORTRAN Version|FORTRAN 77 Compiler|Absoft Fortran Compiler Version|Copyright Absoft Corporation.*?Version))'+\\\n r' (?P<version>[^\\s*,]*)(.*?Absoft Corp|)'\n\n # on windows: f90 -V -c dummy.f\n # f90: Copyright Absoft Corporation 1994-1998 mV2; Cray Research, Inc. 1994-1996 CF90 (2.x.x.x f36t87) Version 2.3 Wed Apr 19, 2006 13:05:16\n\n # samt5735(8)$ f90 -V -c dummy.f\n # f90: Copyright Absoft Corporation 1994-2002; Absoft Pro FORTRAN Version 8.0\n # Note that fink installs g77 as f77, so need to use f90 for detection.\n\n executables = {\n 'version_cmd' : None, # set by update_executables\n 'compiler_f77' : [\"f77\"],\n 'compiler_fix' : [\"f90\"],\n 'compiler_f90' : [\"f90\"],\n 'linker_so' : [\"<F90>\"],\n 'archiver' : [\"ar\", \"-cr\"],\n 'ranlib' : [\"ranlib\"]\n }\n\n if os.name=='nt':\n library_switch = '/out:' #No space after /out:!\n\n module_dir_switch = None\n module_include_switch = '-p'\n\n def update_executables(self):\n f = cyg2win32(dummy_fortran_file())\n self.executables['version_cmd'] = ['<F90>', '-V', '-c',\n f+'.f', '-o', f+'.o']\n\n def get_flags_linker_so(self):\n if os.name=='nt':\n opt = ['/dll']\n # The \"-K shared\" switches are being left in for pre-9.0 versions\n # of Absoft though I don't think versions earlier than 9 can\n # actually be used to build shared libraries. In fact, version\n # 8 of Absoft doesn't recognize \"-K shared\" and will fail.\n elif self.get_version() >= '9.0':\n opt = ['-shared']\n else:\n opt = [\"-K\",\"shared\"]\n return opt\n\n def library_dir_option(self, dir):\n if os.name=='nt':\n return ['-link','/PATH:\"%s\"' % (dir)]\n return \"-L\" + dir\n\n def library_option(self, lib):\n if os.name=='nt':\n return '%s.lib' % (lib)\n return \"-l\" + lib\n\n def get_library_dirs(self):\n opt = FCompiler.get_library_dirs(self)\n d = os.environ.get('ABSOFT')\n if d:\n if self.get_version() >= '10.0':\n # use shared libraries, the static libraries were not compiled -fPIC\n prefix = 'sh'\n else:\n prefix = ''\n if cpu.is_64bit():\n suffix = '64'\n else:\n suffix = ''\n opt.append(os.path.join(d, '%slib%s' % (prefix, suffix)))\n return opt\n\n def get_libraries(self):\n opt = FCompiler.get_libraries(self)\n if self.get_version() >= '11.0':\n opt.extend(['af90math', 'afio', 'af77math', 'amisc'])\n elif self.get_version() >= '10.0':\n opt.extend(['af90math', 'afio', 'af77math', 'U77'])\n elif self.get_version() >= '8.0':\n opt.extend(['f90math','fio','f77math','U77'])\n else:\n opt.extend(['fio','f90math','fmath','U77'])\n if os.name =='nt':\n opt.append('COMDLG32')\n return opt\n\n def get_flags(self):\n opt = FCompiler.get_flags(self)\n if os.name != 'nt':\n opt.extend(['-s'])\n if self.get_version():\n if self.get_version()>='8.2':\n opt.append('-fpic')\n return opt\n\n def get_flags_f77(self):\n opt = FCompiler.get_flags_f77(self)\n opt.extend(['-N22','-N90','-N110'])\n v = self.get_version()\n if os.name == 'nt':\n if v and v>='8.0':\n opt.extend(['-f','-N15'])\n else:\n opt.append('-f')\n if v:\n if v<='4.6':\n opt.append('-B108')\n else:\n # Though -N15 is undocumented, it works with\n # Absoft 8.0 on Linux\n opt.append('-N15')\n return opt\n\n def get_flags_f90(self):\n opt = FCompiler.get_flags_f90(self)\n opt.extend([\"-YCFRL=1\",\"-YCOM_NAMES=LCS\",\"-YCOM_PFX\",\"-YEXT_PFX\",\n \"-YCOM_SFX=_\",\"-YEXT_SFX=_\",\"-YEXT_NAMES=LCS\"])\n if self.get_version():\n if self.get_version()>'4.6':\n opt.extend([\"-YDEALLOC=ALL\"])\n return opt\n\n def get_flags_fix(self):\n opt = FCompiler.get_flags_fix(self)\n opt.extend([\"-YCFRL=1\",\"-YCOM_NAMES=LCS\",\"-YCOM_PFX\",\"-YEXT_PFX\",\n \"-YCOM_SFX=_\",\"-YEXT_SFX=_\",\"-YEXT_NAMES=LCS\"])\n opt.extend([\"-f\",\"fixed\"])\n return opt\n\n def get_flags_opt(self):\n opt = ['-O']\n return opt\n\nif __name__ == '__main__':\n from distutils import log\n log.set_verbosity(2)\n from numpy.distutils.fcompiler import new_fcompiler\n compiler = new_fcompiler(compiler='absoft')\n compiler.customize()\n print(compiler.get_version())\n", "\"\"\"\n========================\nRandom Number Generation\n========================\n\n==================== =========================================================\nUtility functions\n==============================================================================\nrandom Uniformly distributed values of a given shape.\nbytes Uniformly distributed random bytes.\nrandom_integers Uniformly distributed integers in a given range.\nrandom_sample Uniformly distributed floats in a given range.\nrandom Alias for random_sample\nranf Alias for random_sample\nsample Alias for random_sample\nchoice Generate a weighted random sample from a given array-like\npermutation Randomly permute a sequence / generate a random sequence.\nshuffle Randomly permute a sequence in place.\nseed Seed the random number generator.\n==================== =========================================================\n\n==================== =========================================================\nCompatibility functions\n==============================================================================\nrand Uniformly distributed values.\nrandn Normally distributed values.\nranf Uniformly distributed floating point numbers.\nrandint Uniformly distributed integers in a given range.\n==================== =========================================================\n\n==================== =========================================================\nUnivariate distributions\n==============================================================================\nbeta Beta distribution over ``[0, 1]``.\nbinomial Binomial distribution.\nchisquare :math:`\\\\chi^2` distribution.\nexponential Exponential distribution.\nf F (Fisher-Snedecor) distribution.\ngamma Gamma distribution.\ngeometric Geometric distribution.\ngumbel Gumbel distribution.\nhypergeometric Hypergeometric distribution.\nlaplace Laplace distribution.\nlogistic Logistic distribution.\nlognormal Log-normal distribution.\nlogseries Logarithmic series distribution.\nnegative_binomial Negative binomial distribution.\nnoncentral_chisquare Non-central chi-square distribution.\nnoncentral_f Non-central F distribution.\nnormal Normal / Gaussian distribution.\npareto Pareto distribution.\npoisson Poisson distribution.\npower Power distribution.\nrayleigh Rayleigh distribution.\ntriangular Triangular distribution.\nuniform Uniform distribution.\nvonmises Von Mises circular distribution.\nwald Wald (inverse Gaussian) distribution.\nweibull Weibull distribution.\nzipf Zipf's distribution over ranked data.\n==================== =========================================================\n\n==================== =========================================================\nMultivariate distributions\n==============================================================================\ndirichlet Multivariate generalization of Beta distribution.\nmultinomial Multivariate generalization of the binomial distribution.\nmultivariate_normal Multivariate generalization of the normal distribution.\n==================== =========================================================\n\n==================== =========================================================\nStandard distributions\n==============================================================================\nstandard_cauchy Standard Cauchy-Lorentz distribution.\nstandard_exponential Standard exponential distribution.\nstandard_gamma Standard Gamma distribution.\nstandard_normal Standard normal distribution.\nstandard_t Standard Student's t-distribution.\n==================== =========================================================\n\n==================== =========================================================\nInternal functions\n==============================================================================\nget_state Get tuple representing internal state of generator.\nset_state Set state of generator.\n==================== =========================================================\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\n# To get sub-modules\nfrom .info import __doc__, __all__\n\nimport warnings\nfrom numpy.testing.utils import WarningManager\n\nwarn_ctx = WarningManager()\nwarn_ctx.__enter__()\ntry:\n warnings.filterwarnings(\"ignore\", message=\"numpy.ndarray size changed\")\n from .mtrand import *\nfinally:\n warn_ctx.__exit__()\n\n# Some aliases:\nranf = random = sample = random_sample\n__all__.extend(['ranf','random','sample'])\n\ndef __RandomState_ctor():\n \"\"\"Return a RandomState instance.\n\n This function exists solely to assist (un)pickling.\n \"\"\"\n return RandomState()\n\nfrom numpy.testing import Tester\ntest = Tester().test\nbench = Tester().bench\n", "from __future__ import division, print_function\n\nimport os\nimport sys\n\ndef configuration(parent_package='',top_path=None):\n from numpy.distutils.misc_util import Configuration\n from numpy.distutils.system_info import get_info\n config = Configuration('linalg',parent_package,top_path)\n\n config.add_data_dir('tests')\n\n # Configure lapack_lite\n\n src_dir = 'lapack_lite'\n lapack_lite_src = [\n os.path.join(src_dir, 'python_xerbla.c'),\n os.path.join(src_dir, 'zlapack_lite.c'), \n os.path.join(src_dir, 'dlapack_lite.c'),\n os.path.join(src_dir, 'blas_lite.c'), \n os.path.join(src_dir, 'dlamch.c'),\n os.path.join(src_dir, 'f2c_lite.c'),\n os.path.join(src_dir, 'f2c.h'),\n ]\n\n lapack_info = get_info('lapack_opt',0) # and {}\n def get_lapack_lite_sources(ext, build_dir):\n if not lapack_info:\n print(\"### Warning: Using unoptimized lapack ###\")\n return ext.depends[:-1]\n else:\n if sys.platform=='win32':\n print(\"### Warning: python_xerbla.c is disabled ###\")\n return ext.depends[:1]\n return ext.depends[:2]\n\n config.add_extension('lapack_lite',\n sources = [get_lapack_lite_sources],\n depends = ['lapack_litemodule.c'] + lapack_lite_src,\n extra_info = lapack_info\n )\n\n # umath_linalg module\n\n config.add_extension('_umath_linalg',\n sources = [get_lapack_lite_sources],\n depends = ['umath_linalg.c.src'] + lapack_lite_src,\n extra_info = lapack_info,\n libraries = ['npymath'],\n )\n\n return config\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(configuration=configuration)\n", "# http://www.pgroup.com\nfrom __future__ import division, absolute_import, print_function\n\nfrom numpy.distutils.fcompiler import FCompiler\nfrom sys import platform\n\ncompilers = ['PGroupFCompiler']\n\nclass PGroupFCompiler(FCompiler):\n\n compiler_type = 'pg'\n description = 'Portland Group Fortran Compiler'\n version_pattern = r'\\s*pg(f77|f90|hpf|fortran) (?P<version>[\\d.-]+).*'\n\n if platform == 'darwin':\n executables = {\n 'version_cmd' : [\"<F77>\", \"-V\"],\n 'compiler_f77' : [\"pgfortran\", \"-dynamiclib\"],\n 'compiler_fix' : [\"pgfortran\", \"-Mfixed\", \"-dynamiclib\"],\n 'compiler_f90' : [\"pgfortran\", \"-dynamiclib\"],\n 'linker_so' : [\"libtool\"],\n 'archiver' : [\"ar\", \"-cr\"],\n 'ranlib' : [\"ranlib\"]\n }\n pic_flags = ['']\n else:\n executables = {\n 'version_cmd' : [\"<F77>\", \"-V\"],\n 'compiler_f77' : [\"pgfortran\"],\n 'compiler_fix' : [\"pgfortran\", \"-Mfixed\"],\n 'compiler_f90' : [\"pgfortran\"],\n 'linker_so' : [\"pgfortran\",\"-shared\",\"-fpic\"],\n 'archiver' : [\"ar\", \"-cr\"],\n 'ranlib' : [\"ranlib\"]\n }\n pic_flags = ['-fpic']\n\n\n module_dir_switch = '-module '\n module_include_switch = '-I'\n\n def get_flags(self):\n opt = ['-Minform=inform','-Mnosecond_underscore']\n return self.pic_flags + opt\n def get_flags_opt(self):\n return ['-fast']\n def get_flags_debug(self):\n return ['-g']\n\n if platform == 'darwin':\n def get_flags_linker_so(self):\n return [\"-dynamic\", '-undefined', 'dynamic_lookup']\n\nif __name__ == '__main__':\n from distutils import log\n log.set_verbosity(2)\n from numpy.distutils.fcompiler import new_fcompiler\n compiler = new_fcompiler(compiler='pg')\n compiler.customize()\n print(compiler.get_version())\n" ]
[ [ "numpy.ma.nonzero", "numpy.arange", "numpy.atleast_2d", "numpy.ma.zeros", "numpy.compat.sixu", "numpy.ma.masked_array", "numpy.ma.array", "numpy.ma.masked_where", "numpy.zeros" ], [ "numpy.distutils.fcompiler.FCompiler.get_libraries", "numpy.distutils.fcompiler.FCompiler.get_flags", "numpy.distutils.fcompiler.dummy_fortran_file", "numpy.distutils.fcompiler.FCompiler.get_flags_fix", "numpy.distutils.fcompiler.FCompiler.get_flags_f90", "numpy.distutils.cpuinfo.cpu.is_64bit", "numpy.distutils.fcompiler.FCompiler.get_library_dirs", "numpy.distutils.fcompiler.new_fcompiler", "numpy.distutils.fcompiler.FCompiler.get_flags_f77" ], [ "numpy.testing.utils.WarningManager", "numpy.testing.Tester" ], [ "numpy.distutils.system_info.get_info", "numpy.distutils.misc_util.Configuration", "numpy.distutils.core.setup" ], [ "numpy.distutils.fcompiler.new_fcompiler" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.11", "1.19", "1.24", "1.16", "1.23", "1.20", "1.7", "1.12", "1.21", "1.22", "1.14", "1.6", "1.13", "1.9", "1.17", "1.10", "1.18", "1.15", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.11", "1.12", "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": [] }, { "matplotlib": [], "numpy": [ "1.11", "1.19", "1.24", "1.16", "1.23", "1.20", "1.7", "1.12", "1.21", "1.22", "1.14", "1.6", "1.13", "1.9", "1.17", "1.10", "1.18", "1.15", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhanyinx/SPT_analysis
[ "1cf806c1fd6051e7fc998d2860a16bea6aa9de1a" ]
[ "source/spot_detection_tracking/trackmate_xml_2d.py" ]
[ "\"\"\"\\U0001F1EB\\U0001F1EF \\U00002B50 CSV track coordinate to TrackMate XML conversion.\nFiji allows for quick and easy viewing of images. TrackMate can be used to view tracks.\nUnfortunately, it isn't that simple to convert \"normal\" coordinate output into\nTrackMate-viewable format.\nRequires a \"tracks.csv\" file that contains the following columns:\n- x, y: Coordinate positions in x-/y-axis\n- particle: Unique ID assigned to all coordinates along one track\n- frame: Current point in time / frame\n\"\"\"\n\nimport argparse\nimport os\nimport tempfile\nimport xml.dom.minidom\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\nimport pandas as pd\nimport skimage.io\n\n\ndef get_gaps(frames):\n def __longest_consecutive(a):\n \"\"\"Return length of longest consecutive range in list of integers.\"\"\"\n a = set(a)\n longest = 0\n for i in a:\n if i - 1 not in a:\n streak = 0\n while i in a:\n i += 1\n streak += 1\n longest = max(longest, streak)\n return longest\n\n full_length = np.arange(min(frames), max(frames))\n diff = np.setdiff1d(full_length, frames)\n longest = __longest_consecutive(diff)\n total = len(diff)\n return str(longest), str(total), str(len(full_length))\n\n\ndef __create_model(root, spatialunits: str = \"pixel\", timeunits: str = \"sec\"):\n dict_spotfeatures = [\n {\n \"feature\": \"QUALITY\",\n \"name\": \"Quality\",\n \"shortname\": \"Quality\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_X\",\n \"name\": \"X\",\n \"shortname\": \"X\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_Y\",\n \"name\": \"Y\",\n \"shortname\": \"Y\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_Z\",\n \"name\": \"Z\",\n \"shortname\": \"Z\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_T\",\n \"name\": \"T\",\n \"shortname\": \"T\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"FRAME\",\n \"name\": \"Frame\",\n \"shortname\": \"Frame\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"RADIUS\",\n \"name\": \"Radius\",\n \"shortname\": \"R\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"VISIBILITY\",\n \"name\": \"Visibility\",\n \"shortname\": \"Visibility\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"MANUAL_INTEGER_SPOT_FEATURE\",\n \"name\": \"Custom Integer Spot Feature\",\n \"shortname\": \"Integer Spot Feature\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"MANUAL_DOUBLE_SPOT_FEATURE\",\n \"name\": \"Custom Double Spot Feature\",\n \"shortname\": \"Double Spot Feature\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"HAS_MAX_QUALITY_IN_FRAME\",\n \"name\": \"Has max quality\",\n \"shortname\": \"Max Quality\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"MANUAL_COLOR\",\n \"name\": \"Manual spot color\",\n \"shortname\": \"Spot color\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"MEAN_INTENSITY\",\n \"name\": \"Mean intensity\",\n \"shortname\": \"Mean\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MEDIAN_INTENSITY\",\n \"name\": \"Median intensity\",\n \"shortname\": \"Median\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MIN_INTENSITY\",\n \"name\": \"Minimal intensity\",\n \"shortname\": \"Min\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MAX_INTENSITY\",\n \"name\": \"Maximal intensity\",\n \"shortname\": \"Max\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TOTAL_INTENSITY\",\n \"name\": \"Total intensity\",\n \"shortname\": \"Total int.\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"STANDARD_DEVIATION\",\n \"name\": \"Standard deviation\",\n \"shortname\": \"Stdev.\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"ESTIMATED_DIAMETER\",\n \"name\": \"Estimated diameter\",\n \"shortname\": \"Diam.\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"CONTRAST\",\n \"name\": \"Contrast\",\n \"shortname\": \"Constrast\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"SNR\",\n \"name\": \"Signal/Noise, ratio\",\n \"shortname\": \"SNR\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n ]\n\n dict_edgefeatures = [\n {\n \"feature\": \"SPOT_SOURCE_ID\",\n \"name\": \"Source spot ID\",\n \"shortname\": \"Source ID\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"SPOT_TARGET_ID\",\n \"name\": \"Target spot ID\",\n \"shortname\": \"Target ID\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"LINK_COST\",\n \"name\": \"Link cost\",\n \"shortname\": \"Cost\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_TIME\",\n \"name\": \"Time (mean)\",\n \"shortname\": \"T\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_X_LOCATION\",\n \"name\": \"X Location (mean)\",\n \"shortname\": \"X\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_Y_LOCATION\",\n \"name\": \"Y Location (mean)\",\n \"shortname\": \"Y\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_Z_LOCATION\",\n \"name\": \"Z Location (mean)\",\n \"shortname\": \"Z\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"VELOCITY\",\n \"name\": \"Velocity\",\n \"shortname\": \"V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"DISPLACEMENT\",\n \"name\": \"Displacement\",\n \"shortname\": \"D\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MANUAL_COLOR\",\n \"name\": \"Manual edge color\",\n \"shortname\": \"Edge color\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n ]\n\n dict_trackfeatures = [\n {\n \"feature\": \"MANUAL_INTEGER_TRACK_FEATURE\",\n \"name\": \"Custom Integer Track Feature\",\n \"shortname\": \"Integer Track Feature\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"MANUAL_DOUBLE_TRACK_FEATURE\",\n \"name\": \"Custom Double Track Feature\",\n \"shortname\": \"Double Track Feature\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"NUMBER_SPOTS\",\n \"name\": \"Number of spots in track\",\n \"shortname\": \"N spots\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_GAPS\",\n \"name\": \"Number of gaps\",\n \"shortname\": \"Gaps\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"LONGEST_GAP\",\n \"name\": \"Longest gap\",\n \"shortname\": \"Longest gap\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_SPLITS\",\n \"name\": \"Number of split events\",\n \"shortname\": \"Splits\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_MERGES\",\n \"name\": \"Number of merge events\",\n \"shortname\": \"Merges\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_COMPLEX\",\n \"name\": \"Complex points\",\n \"shortname\": \"Complex\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"TRACK_DURATION\",\n \"name\": \"Duration of track\",\n \"shortname\": \"Duration\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_START\",\n \"name\": \"Track start\",\n \"shortname\": \"T start\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_STOP\",\n \"name\": \"Track stop\",\n \"shortname\": \"T stop\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_DISPLACEMENT\",\n \"name\": \"Track displacement\",\n \"shortname\": \"Displacement\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_INDEX\",\n \"name\": \"Track index\",\n \"shortname\": \"Index\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"TRACK_ID\",\n \"name\": \"Track ID\",\n \"shortname\": \"ID\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"TRACK_X_LOCATION\",\n \"name\": \"X Location (mean)\",\n \"shortname\": \"X\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_Y_LOCATION\",\n \"name\": \"Y Location (mean)\",\n \"shortname\": \"Y\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_Z_LOCATION\",\n \"name\": \"Z Location (mean)\",\n \"shortname\": \"Z\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEAN_SPEED\",\n \"name\": \"Mean velocity\",\n \"shortname\": \"Mean V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MAX_SPEED\",\n \"name\": \"Maximal velocity\",\n \"shortname\": \"Max V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MIN_SPEED\",\n \"name\": \"Minimal velocity\",\n \"shortname\": \"Min V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEDIAN_SPEED\",\n \"name\": \"Median velocity\",\n \"shortname\": \"Median V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_STD_SPEED\",\n \"name\": \"Velocity standard deviation\",\n \"shortname\": \"V std\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEAN_QUALITY\",\n \"name\": \"Mean quality\",\n \"shortname\": \"Mean Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MAX_QUALITY\",\n \"name\": \"Maximal quality\",\n \"shortname\": \"Max Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MIN_QUALITY\",\n \"name\": \"Minimal quality\",\n \"shortname\": \"Min Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEDIAN_QUALITY\",\n \"name\": \"Median quality\",\n \"shortname\": \"Median Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_STD_QUALITY\",\n \"name\": \"Quality standard deviation\",\n \"shortname\": \"Q std\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n ]\n # Model\n model = ET.SubElement(root, \"Model\", spatialunits=spatialunits, timeunits=timeunits)\n featuredeclarations = ET.SubElement(model, \"FeatureDeclarations\")\n\n # SpotFeatures\n spotfeatures = ET.SubElement(featuredeclarations, \"SpotFeatures\")\n for dct in dict_spotfeatures:\n _ = ET.SubElement(spotfeatures, \"Feature\", **dct)\n\n # Edgefeatures\n edgefeatures = ET.SubElement(featuredeclarations, \"EdgeFeatures\")\n for dct in dict_edgefeatures:\n _ = ET.SubElement(edgefeatures, \"Feature\", **dct)\n\n # TrackFeatures\n trackfeatures = ET.SubElement(featuredeclarations, \"TrackFeatures\")\n for dct in dict_trackfeatures:\n _ = ET.SubElement(trackfeatures, \"Feature\", **dct)\n\n return model\n\n\ndef __create_allspots(model, df):\n # List of all spots (without tracks)\n allspots = ET.SubElement(model, \"AllSpots\", nspots=str(len(df)))\n spotid = 0\n for frame in df[\"slice\"].unique():\n frame_id = str(float(frame))\n df_frame = df[df[\"slice\"] == frame]\n spotsinframe = ET.SubElement(allspots, \"SpotsInFrame\", frame=str(frame))\n for row in df_frame.iterrows():\n try:\n size = str(row[1][\"size\"] * 2)\n except KeyError:\n size = \"1.0\"\n dict_spot = {\n \"ID\": f\"{spotid:06}\",\n \"name\": f\"ID{spotid:06}\",\n \"QUALITY\": \"1.0\",\n \"POSITION_T\": frame_id,\n \"MAX_INTENSITY\": \"1.0\",\n \"FRAME\": frame_id,\n \"MEDIAN_INTENSITY\": \"1.0\",\n \"VISIBILITY\": \"1\",\n \"MEAN_INTENSITY\": \"1.0\",\n \"TOTAL_INTENSITY\": \"1.0\",\n \"ESTIMATED_DIAMETER\": size,\n \"RADIUS\": \"1.0\",\n \"SNR\": \"1.0\",\n \"POSITION_X\": str(row[1][\"x\"]),\n \"POSITION_Y\": str(row[1][\"y\"]),\n \"STANDARD_DEVIATION\": \"1.0\",\n \"CONTRAST\": \"1.0\",\n \"MANUAL_COLOR\": \"-10921639\",\n \"MIN_INTENSITY\": \"0.0\",\n \"POSITION_Z\": \"1\",\n }\n _ = ET.SubElement(spotsinframe, \"Spot\", **dict_spot)\n spotid = spotid + 1\n\n\ndef __create_alltracks(model, df):\n # List of all tracks\n alltracks = ET.SubElement(model, \"AllTracks\")\n\n\n# for particle in df[\"particle\"].unique():\n# df_track = df[df[\"particle\"] == particle]\n# track_ids = list(df_track.index)\n# frames = np.array(df_track[\"slice\"])\n# longest, total, duration = get_gaps(frames)\n# dict_track = {\n# \"name\": f\"Track_{particle}\",\n# \"TRACK_ID\": str(particle),\n# \"NUMBER_SPOTS\": str(len(frames)),\n# \"NUMBER_GAPS\": longest,\n# \"LONGEST_GAP\": total,\n# \"NUMBER_SPLITS\": \"0\",\n# \"NUMBER_MERGES\": \"0\",\n# \"NUMBER_COMPLEX\": \"0\",\n# \"TRACK_DURATION\": duration,\n# \"TRACK_START\": str(min(frames)),\n# \"TRACK_STOP\": str(max(frames)),\n# \"TRACK_DISPLACEMENT\": \"0.01\",\n# \"TRACK_INDEX\": str(particle),\n# \"TRACK_X_LOCATION\": str(df_track[\"x\"].mean()),\n# \"TRACK_Y_LOCATION\": str(df_track[\"y\"].mean()),\n# \"TRACK_Z_LOCATION\": \"0.1\",\n# \"TRACK_MEAN_SPEED\": \"0.1\",\n# \"TRACK_MAX_SPEED\": \"0.1\",\n# \"TRACK_MIN_SPEED\": \"0.1\",\n# \"TRACK_MEDIAN_SPEED\": \"0.1\",\n# \"TRACK_STD_SPEED\": \"0.1\",\n# \"TRACK_MEAN_QUALITY\": \"0.1\",\n# \"TRACK_MAX_QUALITY\": \"0.1\",\n# \"TRACK_MIN_QUALITY\": \"0.1\",\n# \"TRACK_MEDIAN_QUALITY\": \"0.1\",\n# \"TRACK_STD_QUALITY\": \"0.1\",\n# }\n# track = ET.SubElement(alltracks, \"Track\", **dict_track)\n\n# # Add all spots in the corresponding track\n# for row in df_track.iterrows():\n# dict_edge = {\n# \"SPOT_SOURCE_ID\": f\"{row[0]:06}\",\n# \"SPOT_TARGET_ID\": f\"{track_ids[track_ids.index(row[0]) - 1]:06}\",\n# \"LINK_COST\": \"0.1\",\n# \"EDGE_TIME\": \"0.1\",\n# \"EDGE_X_LOCATION\": str(row[1][\"x\"]),\n# \"EDGE_Y_LOCATION\": str(row[1][\"y\"]),\n# \"EDGE_Z_LOCATION\": \"0.0\",\n# \"VELOCITY\": \"0.1\",\n# \"DISPLACEMENT\": \"0.1\",\n# }\n# _ = ET.SubElement(track, \"Edge\", **dict_edge)\n\n\ndef __create_filteredtracks(model, df):\n # Tracks after TrackMate's filtering\n filteredtracks = ET.SubElement(model, \"FilteredTracks\")\n\n\n# for particle in df[\"particle\"].unique():\n# _ = ET.SubElement(filteredtracks, \"TrackID\", TRACK_ID=str(particle))\n\n\ndef __create_settings(\n root,\n file_image,\n pixelwidth: str = \"1.0\",\n pixelheight: str = \"1.0\",\n voxeldepth: str = \"1.0\",\n timeinterval: str = \"1.0\",\n):\n # Image metadata\n path, fname = os.path.split(file_image)\n image = skimage.io.imread(file_image)\n if len(image.shape) == 2:\n Warning(\n f\"Found image with shape = 2; assuming it's 3d data with a single time point.\"\n )\n image = np.expand_dims(image, axis=0)\n frames, width, height = image.shape\n imagedata = {\n \"filename\": fname,\n \"folder\": path,\n \"width\": str(width),\n \"height\": str(height),\n \"nslices\": \"1\",\n \"nframes\": str(frames),\n \"pixelwidth\": pixelwidth,\n \"pixelheight\": pixelheight,\n \"voxeldepth\": voxeldepth,\n \"timeinterval\": timeinterval,\n }\n basicsettings = {\n \"xstart\": \"0\",\n \"xend\": str(width - 1),\n \"ystart\": \"0\",\n \"yend\": str(height - 1),\n \"zstart\": \"0\",\n \"zend\": \"0\",\n \"tstart\": \"0\",\n \"tend\": str(frames - 1),\n }\n detectorsettings = {\n \"DETECTOR_NAME\": \"LOG_DETECTOR\",\n \"TARGET_CHANNEL\": \"1\",\n \"RADIUS\": \"5.0\",\n \"THRESHOLD\": \"1000.0\",\n \"DO_MEDIAN_FILTERING\": \"false\",\n \"DO_SUBPIXEL_LOCALIZATION\": \"true\",\n }\n initialspotfilter = {\"feature\": \"QUALITY\", \"value\": \"0.0\", \"isabove\": \"true\"}\n dict_trackersettings = {\n \"TRACKER_NAME\": \"SPARSE_LAP_TRACKER\",\n \"CUTOFF_PERCENTILE\": \"0.9\",\n \"ALTERNATIVE_LINKING_COST_FACTOR\": \"1.05\",\n \"BLOCKING_VALUE\": \"Infinity\",\n }\n dict_subtrackersettings = {\n \"Linking\": {\"LINKING_MAX_DISTANCE\": \"0.8\"},\n \"GapClosing\": {\n \"ALLOW_GAP_CLOSING\": \"false\",\n \"GAP_CLOSING_MAX_DISTANCE\": \"0.5\",\n \"MAX_FRAME_GAP\": \"3\",\n },\n \"TrackSplitting\": {\n \"ALLOW_TRACK_SPLITTING\": \"false\",\n \"SPLITTING_MAX_DISTANCE\": \"15.0\",\n },\n \"TrackMerging\": {\n \"ALLOW_TRACK_MERGING\": \"false\",\n \"MERGING_MAX_DISTANCE\": \"15.0\",\n },\n }\n dict_analyzercollection = {\n \"SpotAnalyzers\": [\n \"MANUAL_SPOT_COLOR_ANALYZER\",\n \"Spot descriptive statistics\",\n \"Spot radius estimator\",\n \"Spot contrast and SNR\",\n ],\n \"EdgeAnalyzers\": [\n \"Edge target\",\n \"Edge mean location\",\n \"Edge velocity\",\n \"MANUAL_EDGE_COLOR_ANALYZER\",\n ],\n \"TrackAnalyzers\": [\n \"Branching analyzer\",\n \"Track duration\",\n \"Track index\",\n \"Track location\",\n \"Velocity\",\n \"TRACK_SPOT_QUALITY\",\n ],\n }\n\n # General Settings\n settings = ET.SubElement(root, \"Settings\")\n _ = ET.SubElement(settings, \"ImageData\", **imagedata)\n _ = ET.SubElement(settings, \"BasicSettings\", **basicsettings)\n _ = ET.SubElement(settings, \"DetectorSettings\", **detectorsettings)\n _ = ET.SubElement(settings, \"InitialSpotFilter\", **initialspotfilter)\n _ = ET.SubElement(settings, \"SpotFilterCollection\")\n\n # Tracker settings\n trackersettings = ET.SubElement(settings, \"TrackerSettings\", **dict_trackersettings)\n for k, v in dict_subtrackersettings.items():\n subelement = ET.SubElement(trackersettings, k, **v)\n _ = ET.SubElement(subelement, \"FeaturePenalties\")\n\n # Filter settings\n _ = ET.SubElement(settings, \"TrackFilterCollection\")\n analyzercollection = ET.SubElement(settings, \"AnalyzerCollection\")\n for k, v in dict_analyzercollection.items():\n subanalyzer = ET.SubElement(analyzercollection, k)\n for lst in v:\n _ = ET.SubElement(subanalyzer, \"Analyzer\", key=lst)\n\n\ndef __create_guistate(root):\n # TrackMate's GUI settings\n guistate = ET.SubElement(root, \"GUIState\", state=\"InitialFiltering\")\n for _ in range(4):\n _ = ET.SubElement(guistate, \"View\", key=\"HYPERSTACKDISPLAYER\")\n\n\ndef __pretty_output(root, file_output):\n # Save file after fancy formatting to prettify\n with tempfile.TemporaryDirectory() as tempdirname:\n fname = os.path.join(tempdirname, \"file.xml\")\n tree = ET.ElementTree(root)\n tree.write(fname, encoding=\"UTF-8\", xml_declaration=True)\n dom = xml.dom.minidom.parse(fname)\n pretty_xml = dom.toprettyxml()\n\n with open(file_output, \"w\") as f:\n f.write(pretty_xml)\n\n\ndef create_trackmate_xml(\n spots_df,\n file_image,\n file_output,\n spatialunits: str = \"pixel\",\n timeunits: str = \"sec\",\n pixelwidth: int = 1,\n pixelheight: int = 1,\n voxeldepth: int = 1,\n timeinterval: int = 1,\n):\n # Check required track df columns\n df = spots_df\n df[\"x\"] = df[\"x\"] * pixelwidth\n df[\"y\"] = df[\"y\"] * pixelheight\n df[\"z\"] = 1.0\n\n df.to_csv(file_output.replace(\"xml\", \"csv\"))\n\n req_cols = [\"x\", \"y\", \"slice\"]\n if not all(req in df.columns for req in req_cols):\n raise ValueError(f\"Not all required columns present! {req_cols} must exist.\")\n\n # XML tree\n root = ET.Element(\"TrackMate\", version=\"6.0.1\")\n\n # Model\n model = __create_model(root, spatialunits=spatialunits, timeunits=timeunits)\n __create_allspots(model, df)\n __create_alltracks(model, df)\n __create_filteredtracks(model, df)\n\n # Settings\n __create_settings(\n root,\n file_image,\n pixelwidth=str(pixelwidth),\n pixelheight=str(pixelheight),\n voxeldepth=str(voxeldepth),\n timeinterval=str(timeinterval),\n )\n __create_guistate(root)\n\n # Save output\n __pretty_output(root, file_output)\n" ]
[ [ "numpy.expand_dims", "numpy.setdiff1d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PatrykNeubauer/NeMo
[ "3ada744b884dba5f233f22c6991fc6092c6ca8d0", "3ada744b884dba5f233f22c6991fc6092c6ca8d0" ]
[ "scripts/asr_language_modeling/neural_rescorer/eval_neural_rescorer.py", "nemo/collections/nlp/models/text_classification/text_classification_model.py" ]
[ "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis script would evaluate a neural language model (Transformer) trained with\n`examples/nlp/language_modeling/transformer_lm.py' as a rescorer for ASR systems.\nGiven a trained TransformerLMModel `.nemo` file, this script can be used to re-score the beams obtained from a beam\nsearch decoder of an ASR model.\n\nUSAGE:\n1. Obtain `.tsv` file with beams and their corresponding scores. Scores can be from a regular beam search decoder or\n in fusion with an N-gram LM scores. For a given beam size `beam_size` and a number of examples\n for evaluation `num_eval_examples`, it should contain (`beam_size` x `num_eval_examples`) lines of\n form `beam_candidate_text \\t score`. This file can be generated by `scripts/asr_language_modeling/ngram_lm/eval_beamsearch_ngram.py`.\n\n2. Rescore the candidates:\n python eval_neural_rescorer.py\n --lm_model=[path to .nemo file of the LM]\n --beams_file=[path to beams .tsv file]\n --beam_size=[size of the beams]\n --eval_manifest=[path to eval manifest .json file]\n --batch_size=[batch size used for inference on the LM model]\n --alpha=[the value for the parameter rescorer_alpha]\n --beta=[the value for the parameter rescorer_beta]\n\nYou may find more info on how to use this script at:\nhttps://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/asr_language_modeling.html\n\n\"\"\"\n\nimport contextlib\nimport json\nfrom argparse import ArgumentParser\n\nimport editdistance\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nimport tqdm\n\nfrom nemo.collections.nlp.models.language_modeling import TransformerLMModel\nfrom nemo.utils import logging\n\n\nclass BeamScoresDataset(torch.utils.data.Dataset):\n \"\"\"\n Dataset to read the score file containing the beams and their score\n\n Args:\n data_path: path to the beams file\n tokenizer: tokenizer of the LM model\n manifest_path: manifest `.json` file which contains the ground truths transcripts\n beam_size: the number of beams per sample\n max_seq_length: the maximum length of sequences\n \"\"\"\n\n def __init__(self, data_path, tokenizer, manifest_path, beam_size=128, max_seq_length=256):\n self.data = pd.read_csv(data_path, delimiter=\"\\t\", header=None)\n self.tokenizer = tokenizer\n self.ground_truths = []\n with open(manifest_path, 'r') as f_orig:\n for line in f_orig:\n item = json.loads(line)\n self.ground_truths.append(item['text'])\n self.beam_size = beam_size\n self.max_seq_length = max_seq_length\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n text = str(self.data[0][idx])\n tokens = [self.tokenizer.bos_id] + self.tokenizer.text_to_ids(text) + [self.tokenizer.eos_id]\n input_ids = [self.tokenizer.pad_id] * self.max_seq_length\n input_ids[: len(tokens)] = tokens\n input_ids = np.array(input_ids)\n input_mask = (input_ids != self.tokenizer.pad_id).astype(np.float32)\n acoustic_score = self.data[1][idx]\n dist = editdistance.eval(text.split(), self.ground_truths[idx // self.beam_size].split())\n ref_len = len(self.ground_truths[idx // self.beam_size].split())\n len_in_chars = len(str(self.data[0][idx]))\n return input_ids, input_mask, acoustic_score, dist, ref_len, len_in_chars, idx\n\n\ndef linear_search_wer(\n dists, scores1, scores2, total_len, coef_range=[0, 10], coef_steps=10000, param_name='parameter'\n):\n \"\"\"\n performs linear search to find the best coefficient when two set of scores are getting linearly fused.\n\n Args:\n dists: Tesnor of the distances between the ground truth and the candidates with shape of [number of samples, beam size]\n scores1: Tensor of the first set of scores with shape of [number of samples, beam size]\n scores2: Tensor of the second set of scores with shape of [number of samples, beam size]\n total_len: The total length of all samples\n coef_range: the search range for the coefficient\n coef_steps: the number of steps that the search range would get divided into\n param_name: the name of the parameter to be used in the figure\n\n Output:\n (best coefficient found, best WER achived)\n \"\"\"\n scale = scores1.mean().abs().item() / scores2.mean().abs().item()\n left = coef_range[0] * scale\n right = coef_range[1] * scale\n coefs = np.linspace(left, right, coef_steps)\n\n best_wer = 10000\n best_coef = left\n wers = []\n for coef in coefs:\n scores = scores1 + coef * scores2\n wer = compute_wer(dists, scores, total_len)\n wers.append(wer)\n if wer < best_wer:\n best_wer = wer\n best_coef = coef\n\n plt.plot(coefs, wers)\n plt.title(f'WER% after rescoring with different values of {param_name}')\n plt.ylabel('WER%')\n plt.xlabel(param_name)\n plt.show()\n return best_coef, best_wer\n\n\ndef compute_wer(dists, scores, total_len):\n \"\"\"\n Sorts the candidates based on the scores and calculates the WER with the new top candidates.\n\n Args:\n dists: Tensor of the distances between the ground truth and the candidates with shape of [number of samples, beam size]\n scores: Tensor of the scores for candidates with shape of [number of samples, beam size]\n total_len: The total length of all samples\n\n Output:\n WER with the new scores\n \"\"\"\n indices = scores.max(dim=1, keepdim=True)[1]\n wer = dists.gather(dim=1, index=indices).sum() / total_len\n wer = wer.item()\n return wer\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument(\"--lm_model_file\", type=str, required=True, help=\"path to LM model .nemo file\")\n parser.add_argument(\"--beams_file\", type=str, required=True, help=\"path to beams .tsv file\")\n parser.add_argument(\n \"--eval_manifest\", type=str, required=True, help=\"path to the evaluation `.json` manifest file\"\n )\n parser.add_argument(\"--beam_size\", type=int, required=True, help=\"number of beams per candidate\")\n parser.add_argument(\"--batch_size\", type=int, default=256, help=\"inference batch size\")\n parser.add_argument(\"--alpha\", type=float, default=None, help=\"parameter alpha of the fusion\")\n parser.add_argument(\"--beta\", type=float, default=None, help=\"parameter beta of the fusion\")\n parser.add_argument(\n \"--scores_output_file\", default=None, type=str, help=\"The optional path to store the rescored beams\"\n )\n parser.add_argument(\n \"--device\", default=\"cuda\", type=str, help=\"The device to load the model onto to calculate the scores\"\n )\n parser.add_argument(\n \"--use_amp\", action=\"store_true\", help=\"Whether to use AMP if available to calculate the scores\"\n )\n args = parser.parse_args()\n\n device = args.device\n if device.startswith(\"cuda\") and not torch.cuda.is_available():\n logging.info(f\"cuda is not available! switched to cpu.\")\n device = \"cpu\"\n\n if args.lm_model_file.endswith(\".nemo\"):\n logging.info(\"Attempting to initialize from .nemo file\")\n model = TransformerLMModel.restore_from(\n restore_path=args.lm_model_file, map_location=torch.device(device)\n ).eval()\n else:\n raise NotImplementedError(f\"Only supports .nemo files, but got: {args.model}\")\n\n max_seq_length = model.encoder._embedding.position_embedding.pos_enc.shape[0]\n dataset = BeamScoresDataset(args.beams_file, model.tokenizer, args.eval_manifest, args.beam_size, max_seq_length)\n data_loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=args.batch_size)\n\n if args.use_amp:\n if torch.cuda.is_available() and hasattr(torch.cuda, 'amp') and hasattr(torch.cuda.amp, 'autocast'):\n logging.info(\"AMP is enabled!\\n\")\n autocast = torch.cuda.amp.autocast\n else:\n\n @contextlib.contextmanager\n def autocast():\n yield\n\n logging.info(f\"Rescoring with beam_size: {args.beam_size}\")\n logging.info(\"Calculating the scores...\")\n with autocast():\n with torch.no_grad():\n am_scores, lm_scores, dists, ref_lens, lens_in_chars = [], [], [], [], []\n for batch in tqdm.tqdm(data_loader):\n input_ids, input_mask, acoustic_score, dist, ref_len, len_in_chars, idx = batch\n\n max_len_in_batch = input_mask.sum(dim=0).argmin().item()\n input_ids, input_mask = input_ids[:, :max_len_in_batch], input_mask[:, :max_len_in_batch]\n if torch.cuda.is_available():\n input_ids, input_mask = input_ids.to(device), input_mask.to(device)\n dist, acoustic_score, len_in_chars = (\n dist.to(device),\n acoustic_score.to(device),\n len_in_chars.to(device),\n )\n\n log_probs = model.forward(input_ids[:, :-1], input_mask[:, :-1])\n target_log_probs = log_probs.gather(2, input_ids[:, 1:].unsqueeze(2)).squeeze(2)\n neural_lm_score = torch.sum(target_log_probs * input_mask[:, 1:], dim=-1)\n\n am_scores.append(acoustic_score)\n lm_scores.append(neural_lm_score)\n dists.append(dist)\n ref_lens.append(ref_len)\n lens_in_chars.append(len_in_chars)\n\n am_scores = torch.cat(am_scores).view(-1, args.beam_size)\n lm_scores = torch.cat(lm_scores).view(-1, args.beam_size)\n dists = torch.cat(dists).view(-1, args.beam_size)\n ref_lens = torch.cat(ref_lens).view(-1, args.beam_size)\n lens_in_chars = torch.cat(lens_in_chars).view(-1, args.beam_size).to(am_scores.dtype)\n\n total_len = ref_lens[:, 0].sum()\n model_wer = dists[:, 0].sum() / total_len\n ideal_wer = dists.min(dim=1)[0].sum() / total_len\n\n if args.alpha is None:\n logging.info(\"Linear search for alpha...\")\n coef1, _ = linear_search_wer(\n dists=dists, scores1=am_scores, scores2=lm_scores, total_len=total_len, param_name='alpha'\n )\n coef1 = np.round(coef1, 3)\n logging.info(f\"alpha={coef1} achieved the best WER.\")\n logging.info(f\"------------------------------------------------\")\n else:\n coef1 = args.alpha\n\n scores = am_scores + coef1 * lm_scores\n\n if args.beta is None:\n logging.info(\"Linear search for beta...\")\n coef2, _ = linear_search_wer(\n dists=dists, scores1=scores, scores2=lens_in_chars, total_len=total_len, param_name='beta'\n )\n coef2 = np.round(coef2, 3)\n logging.info(f\"beta={coef2} achieved the best WER.\")\n logging.info(f\"------------------------------------------------\")\n else:\n coef2 = args.beta\n\n new_scores = am_scores + coef1 * lm_scores + coef2 * lens_in_chars\n rescored_wer = compute_wer(dists, new_scores, total_len)\n\n logging.info(f\"Input beams WER: {np.round(model_wer.item() * 100, 2)}%\")\n logging.info(f\"------------------------------------------------\")\n logging.info(f\" +LM rescoring WER: {np.round(rescored_wer * 100, 2)}%\")\n logging.info(f\" with alpha={coef1}, beta={coef2}\")\n logging.info(f\"------------------------------------------------\")\n logging.info(f\"Best possible WER: {np.round(ideal_wer.item() * 100, 2)}%\")\n logging.info(f\"------------------------------------------------\")\n\n new_scores_flatten = new_scores.flatten()\n if args.scores_output_file is not None:\n logging.info(f'Saving the candidates with their new scores at `{args.scores_output_file}`...')\n with open(args.scores_output_file, \"w\") as fout:\n for sample_id in range(len(dataset)):\n fout.write(f\"{dataset.data[0][sample_id]}\\t{new_scores_flatten[sample_id]}\\n\")\n\n\nif __name__ == '__main__':\n main()\n", "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nfrom typing import Dict, List, Optional\n\nimport torch\nfrom omegaconf import DictConfig\nfrom pytorch_lightning import Trainer\n\nfrom nemo.collections.common.losses import CrossEntropyLoss\nfrom nemo.collections.nlp.data.text_classification import TextClassificationDataset, calc_class_weights\nfrom nemo.collections.nlp.metrics.classification_report import ClassificationReport\nfrom nemo.collections.nlp.models.nlp_model import NLPModel\nfrom nemo.collections.nlp.modules.common import SequenceClassifier\nfrom nemo.collections.nlp.modules.common.lm_utils import get_lm_model\nfrom nemo.collections.nlp.parts.utils_funcs import tensor2list\nfrom nemo.core.classes.common import typecheck\nfrom nemo.core.classes.exportable import Exportable\nfrom nemo.core.neural_types import NeuralType\nfrom nemo.utils import logging\n\n__all__ = ['TextClassificationModel']\n\n\nclass TextClassificationModel(NLPModel, Exportable):\n @property\n def input_types(self) -> Optional[Dict[str, NeuralType]]:\n return self.bert_model.input_types\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n return self.classifier.output_types\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n \"\"\"Initializes the BERTTextClassifier model.\"\"\"\n\n # shared params for dataset and data loaders\n self.dataset_cfg = cfg.dataset\n # tokenizer needs to get initialized before the super.__init__()\n # as dataloaders and datasets need it to process the data\n self.setup_tokenizer(cfg.tokenizer)\n\n self.class_weights = None\n\n super().__init__(cfg=cfg, trainer=trainer)\n\n self.bert_model = get_lm_model(\n pretrained_model_name=cfg.language_model.pretrained_model_name,\n config_file=self.register_artifact('language_model.config_file', cfg.language_model.config_file),\n config_dict=cfg.language_model.config,\n checkpoint_file=cfg.language_model.lm_checkpoint,\n vocab_file=self.register_artifact('tokenizer.vocab_file', cfg.tokenizer.vocab_file),\n )\n\n self.classifier = SequenceClassifier(\n hidden_size=self.bert_model.config.hidden_size,\n num_classes=cfg.dataset.num_classes,\n num_layers=cfg.classifier_head.num_output_layers,\n activation='relu',\n log_softmax=False,\n dropout=cfg.classifier_head.fc_dropout,\n use_transformer_init=True,\n idx_conditioned_on=0,\n )\n\n self.create_loss_module()\n\n # setup to track metrics\n self.classification_report = ClassificationReport(\n num_classes=cfg.dataset.num_classes, mode='micro', dist_sync_on_step=True\n )\n\n # register the file containing the labels into the artifacts to get stored in the '.nemo' file later\n if 'class_labels' in cfg and 'class_labels_file' in cfg.class_labels and cfg.class_labels.class_labels_file:\n self.register_artifact('class_labels', cfg.class_labels.class_labels_file)\n\n def create_loss_module(self):\n # create the loss module if it is not yet created by the training data loader\n if not hasattr(self, 'loss'):\n if hasattr(self, 'class_weights') and self.class_weights:\n # You may need to increase the number of epochs for convergence when using weighted_loss\n self.loss = CrossEntropyLoss(weight=self.class_weights)\n else:\n self.loss = CrossEntropyLoss()\n\n @typecheck()\n def forward(self, input_ids, token_type_ids, attention_mask):\n \"\"\"\n No special modification required for Lightning, define it as you normally would\n in the `nn.Module` in vanilla PyTorch.\n \"\"\"\n hidden_states = self.bert_model(\n input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask\n )\n logits = self.classifier(hidden_states=hidden_states)\n return logits\n\n def training_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the training loop with the data from the training dataloader\n passed in as `batch`.\n \"\"\"\n # forward pass\n input_ids, input_type_ids, input_mask, labels = batch\n logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask)\n\n train_loss = self.loss(logits=logits, labels=labels)\n\n lr = self._optimizer.param_groups[0]['lr']\n\n self.log('train_loss', train_loss)\n self.log('lr', lr, prog_bar=True)\n\n return {\n 'loss': train_loss,\n 'lr': lr,\n }\n\n def validation_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the validation loop with the data from the validation dataloader\n passed in as `batch`.\n \"\"\"\n input_ids, input_type_ids, input_mask, labels = batch\n logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask)\n\n val_loss = self.loss(logits=logits, labels=labels)\n\n preds = torch.argmax(logits, axis=-1)\n\n tp, fn, fp, _ = self.classification_report(preds, labels)\n\n return {'val_loss': val_loss, 'tp': tp, 'fn': fn, 'fp': fp}\n\n def validation_epoch_end(self, outputs):\n \"\"\"\n Called at the end of validation to aggregate outputs.\n :param outputs: list of individual outputs of each validation step.\n \"\"\"\n if not outputs:\n return {}\n if self.trainer.testing:\n prefix = 'test'\n else:\n prefix = 'val'\n\n avg_loss = torch.stack([x[f'val_loss'] for x in outputs]).mean()\n\n # calculate metrics and classification report\n precision, recall, f1, report = self.classification_report.compute()\n\n logging.info(f'{prefix}_report: {report}')\n\n self.log(f'{prefix}_loss', avg_loss, prog_bar=True)\n self.log(f'{prefix}_precision', precision)\n self.log(f'{prefix}_f1', f1)\n self.log(f'{prefix}_recall', recall)\n\n self.classification_report.reset()\n\n def test_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the test loop with the data from the test dataloader\n passed in as `batch`.\n \"\"\"\n return self.validation_step(batch, batch_idx)\n\n def test_epoch_end(self, outputs):\n \"\"\"\n Called at the end of test to aggregate outputs.\n :param outputs: list of individual outputs of each test step.\n \"\"\"\n return self.validation_epoch_end(outputs)\n\n def setup_training_data(self, train_data_config: Optional[DictConfig]):\n if not train_data_config or not train_data_config.file_path:\n logging.info(\n f\"Dataloader config or file_path for the train is missing, so no data loader for test is created!\"\n )\n self._test_dl = None\n return\n self._train_dl = self._setup_dataloader_from_config(cfg=train_data_config)\n\n # calculate the class weights to be used in the loss function\n if self.cfg.dataset.class_balancing == 'weighted_loss':\n self.class_weights = calc_class_weights(train_data_config.file_path, self.cfg.dataset.num_classes)\n else:\n self.class_weights = None\n # we need to create/update the loss module by using the weights calculated from the training data\n self.create_loss_module()\n\n def setup_validation_data(self, val_data_config: Optional[DictConfig]):\n if not val_data_config or not val_data_config.file_path:\n logging.info(\n f\"Dataloader config or file_path for the validation is missing, so no data loader for test is created!\"\n )\n self._test_dl = None\n return\n self._validation_dl = self._setup_dataloader_from_config(cfg=val_data_config)\n\n def setup_test_data(self, test_data_config: Optional[DictConfig]):\n if not test_data_config or not test_data_config.file_path:\n logging.info(\n f\"Dataloader config or file_path for the test is missing, so no data loader for test is created!\"\n )\n self._test_dl = None\n return\n self._test_dl = self._setup_dataloader_from_config(cfg=test_data_config)\n\n def _setup_dataloader_from_config(self, cfg: Dict) -> 'torch.utils.data.DataLoader':\n input_file = cfg.file_path\n if not os.path.exists(input_file):\n raise FileNotFoundError(\n f'{input_file} not found! The data should be be stored in TAB-separated files \\n\\\n \"validation_ds.file_path\" and \"train_ds.file_path\" for train and evaluation respectively. \\n\\\n Each line of the files contains text sequences, where words are separated with spaces. \\n\\\n The label of the example is separated with TAB at the end of each line. \\n\\\n Each line of the files should follow the format: \\n\\\n [WORD][SPACE][WORD][SPACE][WORD][...][TAB][LABEL]'\n )\n\n dataset = TextClassificationDataset(\n tokenizer=self.tokenizer,\n input_file=input_file,\n max_seq_length=self.dataset_cfg.max_seq_length,\n num_samples=cfg.get(\"num_samples\", -1),\n shuffle=cfg.shuffle,\n use_cache=self.dataset_cfg.use_cache,\n )\n\n return torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=cfg.batch_size,\n shuffle=cfg.shuffle,\n num_workers=cfg.get(\"num_workers\", 0),\n pin_memory=cfg.get(\"pin_memory\", False),\n drop_last=cfg.get(\"drop_last\", False),\n collate_fn=dataset.collate_fn,\n )\n\n @torch.no_grad()\n def classifytext(self, queries: List[str], batch_size: int = 1, max_seq_length: int = -1) -> List[int]:\n \"\"\"\n Get prediction for the queries\n Args:\n queries: text sequences\n batch_size: batch size to use during inference\n max_seq_length: sequences longer than max_seq_length will get truncated. default -1 disables truncation.\n Returns:\n all_preds: model predictions\n \"\"\"\n # store predictions for all queries in a single list\n all_preds = []\n mode = self.training\n device = next(self.parameters()).device\n try:\n # Switch model to evaluation mode\n self.eval()\n logging_level = logging.get_verbosity()\n logging.set_verbosity(logging.WARNING)\n dataloader_cfg = {\"batch_size\": batch_size, \"num_workers\": 3, \"pin_memory\": False}\n infer_datalayer = self._setup_infer_dataloader(dataloader_cfg, queries, max_seq_length)\n\n for i, batch in enumerate(infer_datalayer):\n input_ids, input_type_ids, input_mask, subtokens_mask = batch\n\n logits = self.forward(\n input_ids=input_ids.to(device),\n token_type_ids=input_type_ids.to(device),\n attention_mask=input_mask.to(device),\n )\n\n preds = tensor2list(torch.argmax(logits, axis=-1))\n all_preds.extend(preds)\n finally:\n # set mode back to its original value\n self.train(mode=mode)\n logging.set_verbosity(logging_level)\n return all_preds\n\n def _setup_infer_dataloader(\n self, cfg: Dict, queries: List[str], max_seq_length: int = -1\n ) -> 'torch.utils.data.DataLoader':\n \"\"\"\n Setup function for a infer data loader.\n\n Args:\n cfg: config dictionary containing data loader params like batch_size, num_workers and pin_memory\n queries: text\n max_seq_length: maximum length of queries, default is -1 for no limit\n Returns:\n A pytorch DataLoader.\n \"\"\"\n dataset = TextClassificationDataset(tokenizer=self.tokenizer, queries=queries, max_seq_length=max_seq_length)\n return torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=cfg[\"batch_size\"],\n shuffle=False,\n num_workers=cfg.get(\"num_workers\", 0),\n pin_memory=cfg.get(\"pin_memory\", False),\n drop_last=False,\n collate_fn=dataset.collate_fn,\n )\n\n @classmethod\n def list_available_models(cls) -> Optional[Dict[str, str]]:\n pass\n\n @classmethod\n def from_pretrained(cls, name: str):\n pass\n" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.title", "numpy.linspace", "torch.cat", "torch.utils.data.DataLoader", "torch.sum", "matplotlib.pyplot.plot", "numpy.round", "torch.no_grad", "torch.cuda.is_available", "torch.device", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "torch.stack", "torch.no_grad", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mattzett/numerical_electromagnetics
[ "07634817ba854a5515c8c31545b735f651878c5e" ]
[ "magnetic_diffusion/diffusion1D.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 21 19:43:50 2022\n\nIllustrating a basic transient magnetic diffusion problem, See Jackson Section 5.18\n\n@author: zettergm\n\"\"\"\n\nimport numpy as np\nimport scipy.sparse.linalg\nimport scipy.sparse\nfrom scipy.special import erf\nimport matplotlib.pyplot as plt\nfrom numpy import pi,sqrt,abs\nfrom difftools import matrix_kernel\n\n# Material parameters\nmu=4*pi*1e-7\nsigma=1e6\nD=1/mu/sigma # equivalent diffusion coefficient\na=1\nH0=1\nnu=1/mu/sigma/a**2\n\n# Size of grid\nlz=250\nNmax=200\nz=np.linspace(-5*a,5*a,lz)\ndz=z[1]-z[0]\ndt = 5*dz**2/D/2 # explicit stabilty limit will results in really slow time stepping; use 5 times larger. \n\n# This could definitely benefit for sparse storage and a banded/tridiagonal solver\n#A=np.exp(-(x**2/2))\nHx=np.zeros(lz)\nindmin=np.argmin(abs(z+a))\nindmax=np.argmin(abs(z-a))\nHx[indmin:indmax]=1\n\n# Matrix defining finite-difference equation for laplacian operator, one-time setup for this problem\nMsparse=matrix_kernel(lz,dt,dz,D)\nrhs=np.zeros( (lz,1) )\n\n# time iterations\nfor n in range(0,Nmax):\n # set up time-dependent part of the problem and solve\n for i in range(1,lz-1):\n rhs[i]=Hx[i]\n rhssparse=scipy.sparse.csr_matrix(np.reshape(rhs,[lz,1]))\n Hx=scipy.sparse.linalg.spsolve(Msparse,rhssparse,use_umfpack=True) # umfpack is overkill for this but will presumably work\n\n # Solution from Jackson eqn. 5.176\n HxJ=H0/2*( erf((1+abs(z)/a)/2/sqrt((n+1)*dt*nu)) + erf((1-abs(z)/a)/2/sqrt((n+1)*dt*nu)) )\n\n # plot results of each time step and pause briefly\n plt.figure(1,dpi=150)\n plt.clf()\n plt.plot(z,HxJ,'o')\n plt.plot(z,Hx)\n plt.xlabel(\"$x$\")\n plt.ylabel(\"$H_x(z)$\")\n plt.title( \"$t$ = %6.4f s\" % ( (n+1)*dt) )\n plt.ylim((0,H0))\n plt.xlim((-2*a,2*a))\n plt.legend( (\"Jackson 5.176\",\"Numerical BTCS\") )\n plt.show()\n plt.pause(0.01)\n\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.abs", "numpy.linspace", "matplotlib.pyplot.title", "numpy.reshape", "matplotlib.pyplot.ylim", "numpy.sqrt", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.clf", "matplotlib.pyplot.xlim", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.pause", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Yang-YiFan/DiracDeltaNet
[ "36487542422d7573fec6e852b9eece18c6cbce21" ]
[ "extensions/utils.py" ]
[ "'''Some helper functions for PyTorch, including:\r\n - get_mean_and_std: calculate the mean and std value of dataset.\r\n - msr_init: net parameter initialization.\r\n - progress_bar: progress bar mimic xlua.progress.\r\n'''\r\nimport os\r\nimport sys\r\nimport time\r\nimport math\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.init as init\r\nimport numpy as np\r\n\r\n\r\n\r\ndef get_mean_and_std(dataset):\r\n '''Compute the mean and std value of dataset.'''\r\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2)\r\n mean = torch.zeros(3)\r\n std = torch.zeros(3)\r\n print('==> Computing mean and std..')\r\n for inputs, targets in dataloader:\r\n for i in range(3):\r\n mean[i] += inputs[:,i,:,:].mean()\r\n std[i] += inputs[:,i,:,:].std()\r\n mean.div_(len(dataset))\r\n std.div_(len(dataset))\r\n return mean, std\r\n\r\ndef init_params(net):\r\n '''Init layer parameters.'''\r\n for m in net.modules():\r\n if isinstance(m, nn.Conv2d):\r\n init.kaiming_normal(m.weight, mode='fan_out')\r\n if m.bias:\r\n init.constant(m.bias, 0)\r\n elif isinstance(m, nn.BatchNorm2d):\r\n init.constant(m.weight, 1)\r\n init.constant(m.bias, 0)\r\n elif isinstance(m, nn.Linear):\r\n init.normal(m.weight, std=1e-3)\r\n if m.bias:\r\n init.constant(m.bias, 0)\r\n\r\n\r\n_, term_width = os.popen('stty size', 'r').read().split()\r\nterm_width = int(term_width)\r\n\r\nTOTAL_BAR_LENGTH = 65.\r\nlast_time = time.time()\r\nbegin_time = last_time\r\ndef progress_bar(current, total, msg=None):\r\n global last_time, begin_time\r\n if current == 0:\r\n begin_time = time.time() # Reset for new bar.\r\n\r\n cur_len = int(TOTAL_BAR_LENGTH*current/total)\r\n rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1\r\n\r\n sys.stdout.write(' [')\r\n for i in range(cur_len):\r\n sys.stdout.write('=')\r\n sys.stdout.write('>')\r\n for i in range(rest_len):\r\n sys.stdout.write('.')\r\n sys.stdout.write(']')\r\n\r\n cur_time = time.time()\r\n step_time = cur_time - last_time\r\n last_time = cur_time\r\n tot_time = cur_time - begin_time\r\n\r\n L = []\r\n L.append(' Step: %s' % format_time(step_time))\r\n L.append(' | Tot: %s' % format_time(tot_time))\r\n if msg:\r\n L.append(' | ' + msg)\r\n\r\n msg = ''.join(L)\r\n sys.stdout.write(msg)\r\n for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3):\r\n sys.stdout.write(' ')\r\n\r\n # Go back to the center of the bar.\r\n for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2):\r\n sys.stdout.write('\\b')\r\n sys.stdout.write(' %d/%d ' % (current+1, total))\r\n\r\n if current < total-1:\r\n sys.stdout.write('\\r')\r\n else:\r\n sys.stdout.write('\\n')\r\n sys.stdout.flush()\r\n\r\ndef format_time(seconds):\r\n days = int(seconds / 3600/24)\r\n seconds = seconds - days*3600*24\r\n hours = int(seconds / 3600)\r\n seconds = seconds - hours*3600\r\n minutes = int(seconds / 60)\r\n seconds = seconds - minutes*60\r\n secondsf = int(seconds)\r\n seconds = seconds - secondsf\r\n millis = int(seconds*1000)\r\n\r\n f = ''\r\n i = 1\r\n if days > 0:\r\n f += str(days) + 'D'\r\n i += 1\r\n if hours > 0 and i <= 2:\r\n f += str(hours) + 'h'\r\n i += 1\r\n if minutes > 0 and i <= 2:\r\n f += str(minutes) + 'm'\r\n i += 1\r\n if secondsf > 0 and i <= 2:\r\n f += str(secondsf) + 's'\r\n i += 1\r\n if millis > 0 and i <= 2:\r\n f += str(millis) + 'ms'\r\n i += 1\r\n if f == '':\r\n f = '0ms'\r\n return f\r\n\r\n\r\nclass Cutout(object):\r\n \"\"\"Randomly mask out one or more patches from an image.\r\n\r\n Args:\r\n n_holes (int): Number of patches to cut out of each image.\r\n length (int): The length (in pixels) of each square patch.\r\n \"\"\"\r\n def __init__(self, n_holes, length):\r\n self.n_holes = n_holes\r\n self.length = length\r\n\r\n def __call__(self, img):\r\n \"\"\"\r\n Args:\r\n img (Tensor): Tensor image of size (C, H, W).\r\n Returns:\r\n Tensor: Image with n_holes of dimension length x length cut out of it.\r\n \"\"\"\r\n h = img.size(1)\r\n w = img.size(2)\r\n\r\n mask = np.ones((h, w), np.float32)\r\n\r\n for n in range(self.n_holes):\r\n y = np.random.randint(h)\r\n x = np.random.randint(w)\r\n\r\n y1 = np.clip(y - self.length // 2, 0, h)\r\n y2 = np.clip(y + self.length // 2, 0, h)\r\n x1 = np.clip(x - self.length // 2, 0, w)\r\n x2 = np.clip(x + self.length // 2, 0, w)\r\n\r\n mask[y1: y2, x1: x2] = 0.\r\n\r\n mask = torch.from_numpy(mask)\r\n mask = mask.expand_as(img)\r\n img = img * mask\r\n\r\n return img" ]
[ [ "torch.nn.init.kaiming_normal", "torch.zeros", "numpy.clip", "torch.utils.data.DataLoader", "torch.from_numpy", "numpy.ones", "torch.nn.init.normal", "torch.nn.init.constant", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
XinYao1994/mindspore
[ "2c1a2bf752a1fde311caddba22633d2f4f63cb4e" ]
[ "tests/ut/python/ops/test_tensor_slice.py" ]
[ "# Copyright 2020 Huawei Technologies Co., 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# ============================================================================\n\"\"\" test_tensor_slice \"\"\"\nimport numpy as np\nimport pytest\n\nfrom mindspore import Tensor\nfrom mindspore import context\nfrom mindspore import dtype as mstype\nfrom mindspore.nn import Cell\n\nfrom ....mindspore_test_framework.mindspore_test import mindspore_test\nfrom ....mindspore_test_framework.pipeline.forward.compile_forward \\\n import pipeline_for_compile_forward_ge_graph_for_case_by_case_config\n\n\nclass NetWorkSlicePositive(Cell):\n def __init__(self):\n super(NetWorkSlicePositive, self).__init__()\n self.tensor_ret0 = Tensor(np.ones([1, 2, 2], np.int32))\n self.tensor_ret1 = Tensor(np.ones([4, 7, 4], np.int32))\n self.tensor_ret2 = Tensor(np.ones([6, 8, 10], np.int32))\n self.tensor_ret3 = Tensor(np.ones([3, 8, 10], np.int32))\n\n def construct(self, tensor):\n ret0 = tensor[3:4:3, 1:5:2, 3:6:2] + self.tensor_ret0\n ret1 = tensor[-6:4:1, 7:-8:-1, ::3] + self.tensor_ret1\n ret2 = tensor[::, ::, ::] + self.tensor_ret2\n ret3 = tensor[::2] + self.tensor_ret3\n return ret0, ret1, ret2, ret3\n\n\nclass NetWorkSliceEllipsis(Cell):\n def __init__(self):\n super(NetWorkSliceEllipsis, self).__init__()\n self.tensor_ret0 = Tensor(np.ones([2, 7, 8], np.int32))\n self.tensor_ret1 = Tensor(np.ones([6, 7, 8, 9], np.int32))\n self.tensor_ret2 = Tensor(np.ones([1, 6, 7, 8, 9], np.int32))\n\n def construct(self, tensor):\n ret0 = tensor[0:4:2, ..., 1] + self.tensor_ret0\n ret1 = tensor[...] + self.tensor_ret1\n ret2 = tensor[None] + self.tensor_ret2\n ret3 = tensor[True] + self.tensor_ret2\n return ret0, ret1, ret2, ret3\n\n\nclass NetWorkReduceDimension(Cell):\n def __init__(self):\n super(NetWorkReduceDimension, self).__init__()\n self.tensor_ret0 = Tensor(np.ones([2, 4, 1], np.int32))\n self.tensor_ret1 = Tensor(np.ones([3, 4], np.int32))\n self.tensor_ret2 = Tensor(np.ones([6, 8], np.int32))\n self.tensor_ret3 = Tensor(np.array(8, np.int32))\n self.tensor_ret4 = Tensor(np.ones([8, 10], np.int32))\n\n def construct(self, tensor):\n ret0 = tensor[0:6:3, 1:5:1, 3:5:2] + self.tensor_ret0\n ret1 = tensor[::2, 1, ::3] + self.tensor_ret1\n ret2 = tensor[::, ::, 0] + self.tensor_ret2\n ret3 = tensor[3, 2, 5] + self.tensor_ret3\n ret4 = tensor[1] + self.tensor_ret4\n return ret0, ret1, ret2, ret3, ret4\n\n\nclass NetWorkStepNegative(Cell):\n def __init__(self):\n super(NetWorkStepNegative, self).__init__()\n self.tensor_ret = Tensor(np.ones([6, 5, 10], np.int32))\n\n def construct(self, tensor):\n ret = tensor[::1, -5::, ::-1] + self.tensor_ret\n return ret\n\n\nclass NetWorkReduceToScalar(Cell):\n def __init__(self):\n super(NetWorkReduceToScalar, self).__init__()\n self.tensor_ret = Tensor(np.array(9, np.int32))\n\n def construct(self, tensor):\n ret = tensor[2, 3, 4] + self.tensor_ret\n return ret\n\n\nclass TensorAssignWithSliceError1(Cell):\n def __init__(self):\n super(TensorAssignWithSliceError1, self).__init__()\n\n def construct(self, a, b):\n a[1:3:-1,::] = b\n return a\n\nclass TensorAssignWithSliceError2(Cell):\n def __init__(self):\n super(TensorAssignWithSliceError2, self).__init__()\n\n def construct(self, a, b):\n a[1:3:-1] = b\n return a\nclass TensorAssignWithSlice2(Cell):\n def __init__(self):\n super(TensorAssignWithSlice2, self).__init__()\n\n def construct(self, a, b):\n a[1:5] = b\n a[3:4] = 5\n a[-1:1:-1] = b\n a[-1:3:-1] = 5\n a[::] = b\n a[::] = 9\n return a\nclass TensorAssignWithSlice(Cell):\n def __init__(self):\n super(TensorAssignWithSlice, self).__init__()\n self.c = 2\n\n def construct(self, a, b):\n a[1:3,::] = b\n a[2:3:,3:] = b\n a[::] = b\n a[::] = self.c\n a[::,::] = b\n a[::,::] = self.c\n a[2:3:,0:, 4:1:-1] = b\n a[2:3:,0:, 4:1:-1] = self.c\n z = a\n return z\n\ndef test_tensor_assign():\n context.set_context(mode=context.GRAPH_MODE, save_graphs=True)\n net = TensorAssignWithSlice()\n net2= TensorAssignWithSlice2()\n net_e1 = TensorAssignWithSliceError1()\n net_e2 = TensorAssignWithSliceError2()\n a = np.arange(60).reshape(3,4,5)\n b = Tensor([1])\n Ta = Tensor(a)\n Ta4d = Tensor(a.reshape(1,3,4,5))\n Tb= Tensor([1,3])\n Tc= Tensor([])\n t = Tensor([1, 2, 3, 4, 5, 6, 7, 8])\n net(Ta, b)\n net2(t, b)\n # Error for A[Slice] = Number\n # 1. A[Slice] = Number, Slice error\n with pytest.raises(ValueError):\n net_e2(t, 2)\n\n # Error for A[Slice] = U, U is a Tensor\n # 1. A[Slice] = U, u.size is error\n with pytest.raises(ValueError):\n net2(t, Tb)\n # 2. A[Slice] = U, U is empty\n with pytest.raises(ValueError):\n net2(t, Tc)\n # 3. A[Slice] = U, U.size error\n with pytest.raises(ValueError):\n net2(t, Tb)\n\n # Error for A[Tuple(Slice...)] = Tensor\n # 1. A[Tuple(Slice...)] = U, U is empty\n with pytest.raises(ValueError):\n net(Ta, Tc)\n # 2. A[Tuple(Slice...)] = U, U.size error\n with pytest.raises(ValueError):\n net(Ta, Tb)\n # 3. A[Tuple(Slice...)] = U, Slice error\n with pytest.raises(ValueError):\n net_e1(Ta, b)\n\n # Error for A[Tuple(Slice...)] = Number\n # 1. A[Tuple(Slice...)] = Number, Slice error\n with pytest.raises(ValueError):\n net_e1(Ta, 2)\n\n net = TensorAssignWithInteger()\n # Error for A[Number] = scalar/Tensor\n # 1. A[Number] = U, U is a Tensor, u.size not match\n with pytest.raises(ValueError):\n net(Ta, Tb)\n with pytest.raises(ValueError):\n net(Ta, Tc)\n # 2. A[Number] = U, the number index error\n with pytest.raises(IndexError):\n net(Ta4d, b)\n\n # Error for A[(n,m)] = scalar/Tensor\n # 1. A[(n,m)] = U, U is a tensor. u.size not match\n net = TensorAssignWithTupleInteger()\n with pytest.raises(ValueError):\n net(Ta, Tc)\n with pytest.raises(ValueError):\n net(Ta, Tb)\n # 2. A[(n,m)] = U, the number index error\n with pytest.raises(IndexError):\n net(Ta4d, b)\n\nclass TensorAssignWithInteger(Cell):\n def __init__(self):\n super(TensorAssignWithInteger, self).__init__()\n\n def construct(self, a, b):\n a[1] = 1\n a[0] = b\n return a\n\nclass TensorAssignWithTupleInteger(Cell):\n def __init__(self):\n super(TensorAssignWithTupleInteger, self).__init__()\n\n def construct(self, a, b):\n a[(1)] = 1\n a[(1)] = b\n a[(1,1)] = b\n a[(1,1)] = 1\n return a\n\nclass TensorAssignWithBoolTensorIndex(Cell):\n def __init__(self):\n super(TensorAssignWithBoolTensorIndex, self).__init__()\n self.t = Tensor(np.arange(60).reshape([3,4,5]), dtype = mstype.float64)\n\n def construct(self, a, b, c, u_tensor, _scalar):\n a[c] = u_scalar\n a[b] = u_tensor\n z = a + self.t\n return z\n\n\nclass TensorAssignWithBoolTensorIndexError(Cell):\n def __init__(self):\n super(TensorAssignWithBoolTensorIndexError, self).__init__()\n\n def construct(self, a, b, c, u_tensor):\n a[b][c] = u_tensor\n return a\n\n\nclass TensorAssignWithBoolTensorIndex2(Cell):\n def __init__(self):\n super(TensorAssignWithBoolTensorIndex2, self).__init__()\n self.t = Tensor(np.arange(6).reshape([2, 3]), dtype=mstype.float64)\n self.t = Tensor(np.arange(60).reshape([3,4,5]), dtype = mstype.float64)\n\n def construct(self, a, u_tensor, _scalar):\n a[a > 8] = u_tensor\n a[a >= 6] = u_scalar\n a[a < 3] = u_scalar\n a[a <= 5] = u_tensor\n a[a == 5] = u_scalar\n z = a + self.t\n return z\n\n\nclass TensorAssignWithBoolTensorIndex2Error(Cell):\n def __init__(self):\n super(TensorAssignWithBoolTensorIndex2Error, self).__init__()\n\n def construct(self, a, u_tensor):\n a[a > 8][a > 5] = u_tensor\n return a\n\n\na = np.random.uniform(1,10,[3,4,5])\nb = a > 5\nc = a < 3\nTa = Tensor(a)\nTb = Tensor(b)\nTc = Tensor(c)\nTd = Tensor([True, True])\nu_tensor = Tensor([1])\nu_tensor_error = Tensor([1, 2])\nt_1d = Tensor([1, 2, 3, 4, 5, 6, 7, 8])\nu_scalar = 5\n\ndef test_tensor_assign_bool_index():\n net1 = TensorAssignWithBoolTensorIndex()\n net2 = TensorAssignWithBoolTensorIndex2()\n net1(Ta, Tb, Tc, u_tensor, u_scalar)\n net1(Ta, Tb, Tc, u_tensor, u_scalar)\n with pytest.raises(ValueError):\n net1(Ta, Td, Tc, u_tensor, u_scalar)\n with pytest.raises(ValueError):\n net1(Ta, u_tensor, Tc, u_tensor, u_scalar)\n with pytest.raises(ValueError):\n net1(Ta, Tb, Td, u_tensor, u_scalar)\n with pytest.raises(ValueError):\n net1(Ta, Tb, Ta, u_tensor, u_scalar)\n with pytest.raises(ValueError):\n net1(Ta, Tb, Tc, u_tensor_error, u_scalar)\n # net1(Ta, u_tensor, Tc, u_tensor_error, u_scalar)\n with pytest.raises(ValueError):\n net2(Ta, u_tensor_error, u_scalar)\n net3 = TensorAssignWithBoolTensorIndexError()\n with pytest.raises(AttributeError):\n net3(Ta, Tb, Tc, u_tensor)\n with pytest.raises(AttributeError):\n net3(Ta, Tb, Tc, u_scalar)\n net4 = TensorAssignWithBoolTensorIndex2Error()\n with pytest.raises(AttributeError):\n net4(Ta, u_tensor)\n with pytest.raises(AttributeError):\n net4(Ta, u_scalar)\n\ntest_cases = [\n ('TensorAssignWithTupleInteger', {\n 'block': TensorAssignWithTupleInteger(),\n 'desc_inputs': [Ta, u_tensor],\n }),\n ('TensorAssignWithInteger', {\n 'block': TensorAssignWithInteger(),\n 'desc_inputs': [Ta, u_tensor],\n }),\n ('TensorAssignWithSlice', {\n 'block': TensorAssignWithSlice(),\n 'desc_inputs': [Ta, u_tensor],\n }),\n ('TensorAssignWithSlice2', {\n 'block': TensorAssignWithSlice2(),\n 'desc_inputs': [t_1d, u_tensor],\n }),\n ('TensorAssignWithBoolTensorIndex', {\n 'block': TensorAssignWithBoolTensorIndex(),\n 'desc_inputs': [Ta, Tb, Tc, u_tensor, u_scalar],\n }),\n ('TensorAssignWithBoolTensorIndex2', {\n 'block': TensorAssignWithBoolTensorIndex2(),\n 'desc_inputs': [Ta, u_tensor, u_scalar],\n }),\n ('SlicePositive', {\n 'block': NetWorkSlicePositive(),\n 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],\n }),\n ('SliceReduceDimension', {\n 'block': NetWorkReduceDimension(),\n 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],\n }),\n ('SliceNegative', {\n 'block': NetWorkStepNegative(),\n 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],\n }),\n ('SliceReduceToScalar', {\n 'block': NetWorkReduceToScalar(),\n 'desc_inputs': [Tensor(np.ones([6, 8, 10], np.int32))],\n }),\n ('TensorSliceEllipsis', {\n 'block': NetWorkSliceEllipsis(),\n 'desc_inputs': [Tensor(np.ones([6, 7, 8, 9], np.int32))],\n }),\n]\n\n\n@mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)\ndef test_compile():\n context.set_context(mode=context.GRAPH_MODE)\n return test_cases\n\n\ndef test_tensor_slice_reduce_out_of_bounds_neg():\n class NetWork(Cell):\n def __init__(self):\n super(NetWork, self).__init__()\n self.tensor_ret = Tensor(np.array(9, np.int32))\n\n def construct(self, tensor):\n ret = tensor[-7, 3, 4]\n return ret\n\n input_tensor = Tensor(np.ones([6, 8, 10], np.int32))\n net = NetWork()\n with pytest.raises(ValueError) as ex:\n net(input_tensor)\n assert \"For 'StridedSlice' the `begin[0]` should be an int and must greater or equal to -6, but got `-7`\" in str(ex.value)\n\n\ndef test_tensor_slice_reduce_out_of_bounds_positive():\n class NetWork(Cell):\n def __init__(self):\n super(NetWork, self).__init__()\n self.tensor_ret = Tensor(np.array(9, np.int32))\n\n def construct(self, tensor):\n ret = tensor[6, 3, 4]\n return ret\n\n input_tensor = Tensor(np.ones([6, 8, 10], np.int32))\n net = NetWork()\n with pytest.raises(ValueError) as ex:\n net(input_tensor)\n assert \"For 'StridedSlice' the `begin[0]` should be an int and must less than 6, but got `6`\" in str(ex.value)\n" ]
[ [ "numpy.arange", "numpy.random.uniform", "numpy.array", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Strasser-Pablo/pipelines
[ "a1d513eb412f3ffd44edf82af2fa7edb05c3b952" ]
[ "components/deprecated/tfx/ExampleGen/CsvExampleGen/with_URI_IO/component.py" ]
[ "from typing import NamedTuple\n\ndef CsvExampleGen(\n output_examples_uri: 'ExamplesUri',\n input_base: str,\n input_config: {'JsonObject': {'data_type': 'proto:tfx.components.example_gen.Input'}},\n output_config: {'JsonObject': {'data_type': 'proto:tfx.components.example_gen.Output'}},\n range_config: {'JsonObject': {'data_type': 'proto:tfx.configs.RangeConfig'}} = None,\n beam_pipeline_args: list = None,\n) -> NamedTuple('Outputs', [\n ('examples_uri', 'ExamplesUri'),\n]):\n from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen as component_class\n\n #Generated code\n import os\n import tempfile\n from tensorflow.io import gfile\n from google.protobuf import json_format, message\n from tfx.types import channel_utils, artifact_utils\n from tfx.components.base import base_executor\n\n arguments = locals().copy()\n\n component_class_args = {}\n\n for name, execution_parameter in component_class.SPEC_CLASS.PARAMETERS.items():\n argument_value = arguments.get(name, None)\n if argument_value is None:\n continue\n parameter_type = execution_parameter.type\n if isinstance(parameter_type, type) and issubclass(parameter_type, message.Message):\n argument_value_obj = parameter_type()\n json_format.Parse(argument_value, argument_value_obj)\n else:\n argument_value_obj = argument_value\n component_class_args[name] = argument_value_obj\n\n for name, channel_parameter in component_class.SPEC_CLASS.INPUTS.items():\n artifact_path = arguments.get(name + '_uri') or arguments.get(name + '_path')\n if artifact_path:\n artifact = channel_parameter.type()\n artifact.uri = artifact_path.rstrip('/') + '/' # Some TFX components require that the artifact URIs end with a slash\n if channel_parameter.type.PROPERTIES and 'split_names' in channel_parameter.type.PROPERTIES:\n # Recovering splits\n subdirs = gfile.listdir(artifact_path)\n # Workaround for https://github.com/tensorflow/tensorflow/issues/39167\n subdirs = [subdir.rstrip('/') for subdir in subdirs]\n split_names = [subdir.replace('Split-', '') for subdir in subdirs]\n artifact.split_names = artifact_utils.encode_split_names(sorted(split_names))\n component_class_args[name] = channel_utils.as_channel([artifact])\n\n component_class_instance = component_class(**component_class_args)\n\n input_dict = channel_utils.unwrap_channel_dict(component_class_instance.inputs.get_all())\n output_dict = {}\n exec_properties = component_class_instance.exec_properties\n\n # Generating paths for output artifacts\n for name, channel in component_class_instance.outputs.items():\n artifact_path = arguments.get('output_' + name + '_uri') or arguments.get(name + '_path')\n if artifact_path:\n artifact = channel.type()\n artifact.uri = artifact_path.rstrip('/') + '/' # Some TFX components require that the artifact URIs end with a slash\n artifact_list = [artifact]\n channel._artifacts = artifact_list\n output_dict[name] = artifact_list\n\n print('component instance: ' + str(component_class_instance))\n\n executor_context = base_executor.BaseExecutor.Context(\n beam_pipeline_args=arguments.get('beam_pipeline_args'),\n tmp_dir=tempfile.gettempdir(),\n unique_id='tfx_component',\n )\n executor = component_class_instance.executor_spec.executor_class(executor_context)\n executor.Do(\n input_dict=input_dict,\n output_dict=output_dict,\n exec_properties=exec_properties,\n )\n\n return (output_examples_uri, )\n" ]
[ [ "tensorflow.io.gfile.listdir" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AcudoDev/FinanceToolbox
[ "90676e798f2e8eac164ccfcd6708cc717e1911f2" ]
[ "Other/GaussianRandomStockPrice.py" ]
[ "import pandas as pd\nimport numpy as np\n\nimport yfinance as yf\nfrom sklearn.linear_model import LinearRegression\nimport statsmodels\nimport statsmodels.api as sm\nimport statsmodels.tsa.stattools as ts\n\nimport datetime\n\nimport scipy.stats\nimport math\nimport openpyxl as pyxl\nfrom scipy import signal\nfrom scipy import stats as ss\nimport statistics\n\nfrom finta import TA\nfrom filterpy.kalman import KalmanFilter\nfrom filterpy.common import Q_discrete_white_noise\n\nimport pandas_ta as ta\nfrom pingouin import gzscore\n\n\ndef GaussianRandomStockPrice(mu, sigma, n, end, freq, S0=100):\n \"\"\"\n This function randomly creates a stock price series bases on gaussian probabilities.\n\n Arguments:\n ----------\n - mu: float\n The mean parameter\n - sigma: float\n The standard déviation parameter\n - n: int\n Number of periods\n - end: datetime date\n The last date of thé series\n - freq: pandas frequency string\n The frequency of thé dataseries:\n - \"D\": days\n - \"min\": minutes\n - \"s\": seconds\n - S0: float\n The first stock price\n\n Return:\n ----------\n - RStock: Pandas DataFrame\n Contains thé datetime as index and thé random stock prices in a column\n\n \"\"\"\n\n RStock = np.random.normal(mu, sigma, n).astype(\"float\")\n RStock = pd.DataFrame(RStock)\n RStock.rename(inplace=True, columns={RStock.columns[0]: \"Return\"})\n RStock[\"Price\"] = ((1 + RStock[\"Return\"]).cumprod()) * S0\n times = pd.date_range(end=end, freq=freq, periods=n)\n\n RStock.index = times\n RStock = pd.DataFrame(RStock[\"Price\"])\n\n return RStock\n" ]
[ [ "numpy.random.normal", "pandas.DataFrame", "pandas.date_range" ] ]
[ { "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": [], "tensorflow": [] } ]
UCLA-SEAL/QDiff
[ "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819", "d968cbc47fe926b7f88b4adf10490f1edd6f8819" ]
[ "data/p3BR/R2/benchmark/startQiskit289.py", "benchmark/startQiskit2375.py", "data/p3BR/R1/benchmark/startQiskit_QC456.py", "benchmark/startQiskit_Class2296.py", "data/p4VQE/R4/benchmark/startQiskit_noisy62.py", "benchmark/startQiskit_noisy2042.py", "benchmark/startQiskit2925.py", "benchmark/startQiskit_Class2285.py", "benchmark/startQiskit_QC2348.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class124.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class182.py", "data/p4VQE/R4/benchmark/startQiskit_QC277.py", "benchmark/startQiskit_Class3343.py", "benchmark/startQiskit1590.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit336.py", "benchmark/startQiskit_noisy2320.py", "data/p3BR/R2/benchmark/startQiskit_noisy43.py", "data/p4VQE/R2/benchmark/startQiskit_QC77.py", "benchmark/startQiskit1126.py", "benchmark/startQiskit_noisy2660.py", "data/p4VQE/R4/benchmark/startQiskit92.py", "data/p3BR/R2/benchmark/startQiskit_Class364.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class143.py", "benchmark/startQiskit_Class3399.py", "benchmark/startQiskit_noisy3345.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit250.py", "benchmark/startQiskit_QC1883.py", "benchmark/startQiskit_noisy3210.py", "data/p3BR/R1/benchmark/startQiskit_Class408.py", "benchmark/startQiskit_noisy1314.py", "data/p4VQE/R4/benchmark/startQiskit_QC575.py", "benchmark/startQiskit_QC1911.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class230.py", "benchmark/startQiskit_QC1786.py", "data/p4VQE/R4/benchmark/startQiskit_noisy116.py", "benchmark/startQiskit1740.py", "benchmark/startQiskit_Class2002.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class145.py", "data/p3BR/R1/benchmark/startQiskit_Class179.py", "benchmark/startQiskit_noisy1883.py", "data/p2DJ/New/R2/benchmark/startQiskit_QC79.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit78.py", "data/p2DJ/New/R2/benchmark/startQiskit_noisy126.py", "benchmark/startQiskit_noisy2692.py", "benchmark/startQiskit3377.py", "data/p3BR/R1/benchmark/startQiskit_Class446.py", "benchmark/startQiskit_Class1162.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit350.py", "benchmark/startQiskit_QC2209.py", "data/p3BR/R2/benchmark/startQiskit_noisy360.py", "benchmark/startQiskit_QC1309.py", "benchmark/startQiskit_QC2602.py", "benchmark/startQiskit_Class2396.py", "data/p4VQE/R4/benchmark/startQiskit_Class295.py", "benchmark/startQiskit_Class1550.py", "benchmark/startQiskit_noisy1088.py", "benchmark/startQiskit_Class3224.py", "benchmark/startQiskit_QC3361.py", "data/p4VQE/R4/benchmark/startQiskit_QC727.py", "data/p4VQE/R4/benchmark/startQiskit_QC419.py", "data/p3BR/R1/benchmark/startQiskit_QC2.py", "benchmark/startQiskit_noisy1025.py", "benchmark/startQiskit_Class1753.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class25.py", "benchmark/startQiskit_noisy2334.py", "benchmark/startQiskit_QC2212.py", "data/cirq_new/cirq_program/startCirq_Class863.py", "benchmark/startQiskit1493.py", "benchmark/startQiskit_QC1321.py", "benchmark/startQiskit_Class2071.py", "benchmark/startQiskit_Class2221.py", "data/cirq_new/cirq_program/startCirq_Class840.py", "data/p3BR/R2/benchmark/startQiskit_QC292.py", "data/cirq_new/cirq_program/startCirq_Class18.py", "benchmark/startQiskit953.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class137.py", "benchmark/startQiskit_noisy1996.py", "data/p4VQE/R1/benchmark/startQiskit_Class82.py", "benchmark/startQiskit843.py", "data/p4VQE/R4/benchmark/startQiskit_noisy696.py", "benchmark/startQiskit1005.py", "benchmark/startQiskit_QC2449.py", "data/cirq_new/cirq_program/startCirq_Class485.py", "data/p3BR/R2/benchmark/startQiskit166.py", "data/p3BR/R2/benchmark/startQiskit_noisy401.py", "benchmark/startQiskit_Class2024.py", "benchmark/startQiskit2679.py", "data/p3BR/R1/benchmark/startQiskit_QC338.py", "data/p4VQE/R4/benchmark/startQiskit_noisy676.py", "data/p3BR/R1/benchmark/startQiskit_noisy324.py", "data/p3BR/R1/benchmark/startQiskit_QC121.py", "data/p4VQE/R4/benchmark/startQiskit_noisy163.py", "benchmark/startQiskit3286.py", "benchmark/startQiskit_QC3118.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class159.py", "benchmark/startQiskit_noisy2201.py", "benchmark/startQiskit_Class3016.py", "data/p4VQE/R4/benchmark/startQiskit252.py", "benchmark/startQiskit_noisy1591.py", "data/p4VQE/R4/benchmark/startQiskit_Class718.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit332.py", "benchmark/startQiskit1658.py", "data/p4VQE/R4/benchmark/startQiskit_noisy666.py", "benchmark/startQiskit_QC1938.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class80.py", "data/p4VQE/R4/benchmark/startQiskit113.py", "benchmark/startQiskit_QC1184.py", "benchmark/startQiskit_Class1390.py", "benchmark/startQiskit3021.py", "data/p4VQE/R4/benchmark/startQiskit_Class54.py", "data/cirq_new/cirq_program/startCirq_Class729.py", "benchmark/startQiskit_Class2970.py", "data/p4VQE/R4/benchmark/startQiskit_noisy740.py", "benchmark/startQiskit_Class2629.py", "data/p4VQE/R4/benchmark/startQiskit457.py", "data/cirq_new/cirq_program/startCirq_Class366.py", "data/p3BR/R2/benchmark/startQiskit_Class273.py", "benchmark/startQiskit_Class1394.py", "data/p4VQE/R4/benchmark/startQiskit_Class528.py", "data/p3BR/R1/benchmark/startQiskit_noisy345.py", "benchmark/startQiskit_noisy3179.py", "data/p4VQE/R4/benchmark/startQiskit_QC162.py", "benchmark/startQiskit_QC1857.py", "benchmark/startQiskit_noisy1879.py", "benchmark/startQiskit_Class992.py", "data/cirq_new/cirq_program/startCirq_Class796.py", "benchmark/startQiskit1033.py", "data/p4VQE/R4/benchmark/startQiskit_noisy558.py", "benchmark/startQiskit_Class2808.py", "benchmark/startQiskit_QC2896.py", "benchmark/startQiskit2868.py", "benchmark/startQiskit1686.py", "benchmark/startQiskit_noisy1292.py", "data/p3BR/R2/benchmark/startQiskit228.py", "benchmark/startQiskit1827.py", "data/p4VQE/R1/benchmark/startQiskit_Class107.py", "benchmark/startQiskit_Class3334.py", "data/p3BR/R2/benchmark/startQiskit_noisy320.py", "data/p2DJ/New/program/qiskit/noisy/startQiskit_noisy267.py", "benchmark/startQiskit1342.py", "data/p3BR/R2/benchmark/startQiskit_Class245.py", "benchmark/startQiskit_noisy2948.py", "benchmark/startQiskit_QC2748.py", "data/p4VQE/R1/benchmark/startQiskit_noisy127.py", "data/cirq_new/cirq_program/startCirq_Class505.py", "benchmark/startQiskit_QC2033.py", "data/p4VQE/R4/benchmark/startQiskit_noisy346.py", "data/p4VQE/R4/benchmark/startQiskit_QC0.py", "data/p2DJ/New/R2/benchmark/startQiskit_QC81.py", "data/p4VQE/R4/benchmark/startQiskit_QC604.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit7.py", "benchmark/startQiskit1039.py", "benchmark/startQiskit_QC2783.py", "data/p4VQE/R1/benchmark/startQiskit_Class63.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC133.py", "data/p3BR/R2/benchmark/startQiskit_QC167.py", "data/p2DJ/New/R2/benchmark/startQiskit_noisy184.py", "benchmark/startQiskit_QC2733.py", "benchmark/startQiskit_QC3166.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC87.py", "data/p4VQE/R1/benchmark/startQiskit_noisy107.py", "data/p4VQE/R4/benchmark/startQiskit_noisy236.py", "benchmark/startQiskit_Class2248.py", "data/p4VQE/R4/benchmark/startQiskit_noisy494.py", "data/p4VQE/R4/benchmark/startQiskit_noisy63.py", "benchmark/startQiskit_QC1249.py", "data/p3BR/R1/benchmark/startQiskit_QC280.py", "data/p3BR/R1/benchmark/startQiskit_noisy115.py", "data/p4VQE/R4/benchmark/startQiskit_Class636.py", "benchmark/startQiskit_Class1895.py", "benchmark/startQiskit_noisy1324.py", "data/p4VQE/R4/benchmark/startQiskit_QC743.py", "data/p4VQE/R4/benchmark/startQiskit409.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC78.py", "benchmark/startQiskit_Class1348.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit55.py", "benchmark/startQiskit_Class3168.py", "benchmark/startQiskit_Class3207.py", "benchmark/startQiskit_QC2261.py", "data/p3BR/R2/benchmark/startQiskit_Class376.py", "benchmark/startQiskit_Class1400.py", "benchmark/startQiskit_noisy2007.py", "benchmark/startQiskit_noisy1981.py", "benchmark/startQiskit_noisy1797.py", "benchmark/startQiskit_noisy861.py", "data/cirq_new/cirq_program/startCirq_Class240.py", "benchmark/startQiskit_QC1424.py", "data/cirq_new/cirq_program/startCirq_Class26.py", "data/p4VQE/R4/benchmark/startQiskit_Class656.py", "benchmark/startQiskit_noisy2242.py", "benchmark/startQiskit_Class2350.py", "data/p4VQE/R4/benchmark/startQiskit_Class585.py", "benchmark/startQiskit_Class1773.py", "benchmark/startQiskit873.py", "data/p3BR/R1/benchmark/startQiskit_Class410.py", "data/p4VQE/R1/benchmark/startQiskit_noisy132.py", "data/p4VQE/R4/benchmark/startQiskit_noisy600.py", "data/p3BR/R1/benchmark/startQiskit_noisy118.py", "benchmark/startQiskit_QC1762.py", "benchmark/startQiskit_Class2104.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class180.py", "benchmark/startQiskit_Class3188.py", "benchmark/startQiskit_noisy2151.py", "data/p3BR/R2/benchmark/startQiskit414.py", "data/p3BR/R2/benchmark/startQiskit_noisy330.py", "data/p4VQE/R4/benchmark/startQiskit621.py", "data/p3BR/R2/benchmark/startQiskit_Class54.py", "data/p4VQE/R4/benchmark/startQiskit_noisy481.py", "data/p4VQE/R4/benchmark/startQiskit61.py", "benchmark/startQiskit1326.py", "benchmark/startQiskit2199.py", "benchmark/startQiskit_QC2545.py", "data/p4VQE/R4/benchmark/startQiskit267.py", "data/p3BR/R1/benchmark/startQiskit_noisy47.py", "benchmark/startQiskit_QC1042.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class16.py", "benchmark/startQiskit_Class2855.py", "data/p4VQE/R4/benchmark/startQiskit708.py", "benchmark/startQiskit_QC1197.py", "data/p3BR/R1/benchmark/startQiskit_Class189.py", "data/cirq_new/cirq_program/startCirq_Class451.py", "data/p4VQE/R1/benchmark/startQiskit_Class129.py", "data/p4VQE/R4/benchmark/startQiskit_Class287.py", "benchmark/startQiskit_Class2654.py", "data/p3BR/R1/benchmark/startQiskit_Class77.py", "benchmark/startQiskit_noisy2039.py", "data/p4VQE/R4/benchmark/startQiskit_QC560.py", "benchmark/startQiskit_Class1599.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class8.py", "data/p4VQE/R4/benchmark/startQiskit_QC242.py", "benchmark/startQiskit_Class1613.py", "data/p3BR/R1/benchmark/startQiskit_QC9.py", "benchmark/startQiskit_Class2275.py", "data/p2DJ/New/program/qiskit/noisy/startQiskit_noisy182.py", "data/p3BR/R2/benchmark/startQiskit_Class205.py", "benchmark/startQiskit_noisy1635.py", "data/p4VQE/R4/benchmark/startQiskit_QC247.py", "benchmark/startQiskit_noisy2136.py", "benchmark/startQiskit_QC837.py", "data/p3BR/R2/benchmark/startQiskit346.py", "benchmark/startQiskit_noisy2102.py", "data/p4VQE/R4/benchmark/startQiskit271.py", "benchmark/startQiskit3211.py", "benchmark/startQiskit860.py", "benchmark/startQiskit_QC1964.py", "benchmark/startQiskit_noisy929.py", "data/p4VQE/R4/benchmark/startQiskit_QC167.py", "benchmark/startQiskit_Class2573.py", "data/p4VQE/R4/benchmark/startQiskit_QC329.py", "benchmark/startQiskit_noisy1471.py", "benchmark/startQiskit1595.py", "data/p3BR/R2/benchmark/startQiskit372.py", "data/p3BR/R2/benchmark/startQiskit373.py", "data/p3BR/R1/benchmark/startQiskit_QC153.py", "benchmark/startQiskit_Class1018.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC163.py", "benchmark/startQiskit_Class2186.py", "data/p3BR/R2/benchmark/startQiskit_noisy219.py", "benchmark/startQiskit_noisy2519.py", "data/p3BR/R2/benchmark/startQiskit_QC174.py", "benchmark/startQiskit_Class2885.py", "benchmark/startQiskit_noisy1821.py", "data/p4VQE/R4/benchmark/startQiskit_noisy669.py", "benchmark/startQiskit2585.py", "data/p4VQE/R1/benchmark/startQiskit_QC199.py", "data/p4VQE/R1/benchmark/startQiskit_QC73.py", "data/p2DJ/New/program/qiskit/noisy/startQiskit_noisy214.py", "data/p4VQE/R2/benchmark/startQiskit_noisy16.py", "benchmark/startQiskit_noisy1199.py", "data/p3BR/R1/benchmark/startQiskit_QC49.py", "data/p3BR/R1/benchmark/startQiskit_Class120.py", "data/p4VQE/R4/benchmark/startQiskit823.py", "data/p3BR/R2/benchmark/startQiskit145.py", "data/p3BR/R2/benchmark/startQiskit_noisy161.py", "data/p4VQE/R4/benchmark/startQiskit_QC537.py", "data/p4VQE/R4/benchmark/startQiskit_Class304.py", "benchmark/startQiskit_QC1326.py", "benchmark/startQiskit1265.py", "data/p4VQE/R2/benchmark/startQiskit_QC96.py", "data/p4VQE/R1/benchmark/startQiskit_QC110.py", "data/p4VQE/R4/benchmark/startQiskit577.py", "benchmark/startQiskit_Class2128.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class17.py", "benchmark/startQiskit2506.py", "benchmark/startQiskit_noisy3190.py", "benchmark/startQiskit_Class2954.py", "benchmark/startQiskit_noisy2429.py", "benchmark/startQiskit_noisy2105.py", "benchmark/startQiskit_noisy1863.py", "benchmark/startQiskit_noisy1261.py", "benchmark/startQiskit859.py", "benchmark/startQiskit904.py", "data/p2DJ/New/R2/benchmark/startQiskit_noisy39.py", "data/p3BR/R2/benchmark/startQiskit_noisy246.py", "benchmark/startQiskit_Class3104.py", "data/cirq_new/cirq_program/startCirq_Class672.py", "data/p4VQE/R2/benchmark/startQiskit_noisy26.py", "data/p3BR/R2/benchmark/startQiskit_Class366.py", "benchmark/startQiskit_Class2559.py", "benchmark/startQiskit3076.py", "data/p4VQE/R1/benchmark/startQiskit176.py", "benchmark/startQiskit_Class1851.py", "benchmark/startQiskit_noisy1220.py", "benchmark/startQiskit_Class1297.py", "benchmark/startQiskit_Class1922.py", "benchmark/startQiskit_noisy1229.py", "benchmark/startQiskit_noisy1349.py", "benchmark/startQiskit_QC2980.py", "benchmark/startQiskit_noisy2726.py", "benchmark/startQiskit_Class2518.py", "benchmark/startQiskit931.py", "data/p3BR/R2/benchmark/startQiskit_QC29.py", "benchmark/startQiskit_noisy2530.py", "data/p3BR/R1/benchmark/startQiskit_Class20.py", "benchmark/startQiskit_Class2579.py", "benchmark/startQiskit3024.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class157.py", "data/cirq_new/cirq_program/startCirq_Class185.py", "data/p3BR/R1/benchmark/startQiskit_QC52.py", "data/p4VQE/R4/benchmark/startQiskit_noisy89.py", "benchmark/startQiskit2645.py", "data/cirq_new/cirq_program/startCirq_Class974.py", "benchmark/startQiskit2110.py", "data/p4VQE/R2/benchmark/startQiskit_noisy23.py", "benchmark/startQiskit2203.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class7.py", "benchmark/startQiskit2682.py", "benchmark/startQiskit2378.py", "benchmark/startQiskit947.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class5.py", "data/p3BR/R2/benchmark/startQiskit_noisy231.py", "data/p4VQE/R2/benchmark/startQiskit_QC48.py", "benchmark/startQiskit2161.py", "benchmark/startQiskit_QC1638.py", "data/p4VQE/R4/benchmark/startQiskit450.py", "benchmark/startQiskit_Class2749.py", "benchmark/startQiskit_noisy2440.py", "benchmark/startQiskit2529.py", "data/p4VQE/R4/benchmark/startQiskit_noisy541.py", "benchmark/startQiskit_noisy1363.py", "benchmark/startQiskit_QC1572.py", "data/p3BR/R1/benchmark/startQiskit_QC363.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC106.py", "benchmark/startQiskit_noisy1209.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class336.py", "data/p3BR/R2/benchmark/startQiskit_QC271.py", "benchmark/startQiskit_Class2219.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC118.py", "data/cirq_new/cirq_program/startCirq_Class518.py", "benchmark/startQiskit_Class947.py", "benchmark/startQiskit_Class1396.py", "data/cirq_new/cirq_program/startCirq_Class132.py", "benchmark/startQiskit_noisy3012.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC303.py", "benchmark/startQiskit_noisy2957.py", "benchmark/startQiskit_QC1565.py", "data/p3BR/R1/benchmark/startQiskit_Class127.py", "data/p3BR/R1/benchmark/startQiskit_noisy37.py", "data/p3BR/R1/benchmark/startQiskit_QC133.py", "data/p4VQE/R4/benchmark/startQiskit_QC626.py", "benchmark/startQiskit_Class2740.py", "benchmark/startQiskit_noisy3346.py", "benchmark/startQiskit_noisy1819.py", "data/p4VQE/R4/benchmark/startQiskit_Class492.py", "benchmark/startQiskit_QC2205.py", "benchmark/startQiskit2346.py", "data/p4VQE/R4/benchmark/startQiskit_QC782.py", "benchmark/startQiskit_QC1163.py", "benchmark/startQiskit_Class2424.py", "benchmark/startQiskit_Class2351.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit89.py", "WrongBehavior/Found_errors/Pyquil4/startPyquil149.py", "data/p3BR/R1/benchmark/startQiskit_Class237.py", "benchmark/startQiskit_noisy918.py", "benchmark/startQiskit1145.py", "benchmark/startQiskit_QC1868.py", "data/p2DJ/New/R2/benchmark/startQiskit_noisy144.py", "data/p3BR/R1/benchmark/startQiskit_QC357.py", "benchmark/startQiskit1090.py", "benchmark/startQiskit_QC2436.py", "benchmark/startQiskit_Class931.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit61.py", "data/p4VQE/R2/benchmark/startQiskit_QC36.py", "benchmark/startQiskit_noisy2803.py", "benchmark/startQiskit2566.py", "data/p3BR/R1/benchmark/startQiskit_Class159.py", "data/cirq_new/cirq_program/startCirq_Class68.py", "benchmark/startQiskit_QC1691.py", "benchmark/startQiskit_noisy2782.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC212.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit207.py", "data/p4VQE/R1/benchmark/startQiskit_QC21.py", "data/p3BR/R1/benchmark/startQiskit_Class123.py", "benchmark/startQiskit_Class839.py", "benchmark/startQiskit_Class3062.py", "benchmark/startQiskit_QC2969.py", "data/p2DJ/New/program/qiskit/noisy/startQiskit_noisy208.py", "data/p3BR/R1/benchmark/startQiskit_Class403.py", "data/p4VQE/R4/benchmark/startQiskit_noisy12.py", "benchmark/startQiskit_noisy954.py", "data/cirq_new/cirq_program/startCirq_Class387.py", "benchmark/startQiskit_QC933.py", "data/p4VQE/R1/benchmark/startQiskit61.py", "benchmark/startQiskit_QC2807.py", "data/p2DJ/New/program/qiskit/simulator/startQiskit365.py", "benchmark/startQiskit_QC3054.py", "data/p3BR/R2/benchmark/startQiskit_noisy239.py", "benchmark/startQiskit2536.py", "benchmark/startQiskit_QC1476.py", "benchmark/startQiskit_noisy1149.py", "data/p2DJ/New/program/qiskit/QC/startQiskit_QC349.py", "data/p4VQE/R4/benchmark/startQiskit_QC330.py", "benchmark/startQiskit1617.py", "benchmark/startQiskit_Class2099.py", "data/cirq_new/cirq_program/startCirq_Class319.py", "benchmark/startQiskit_noisy2217.py", "data/p4VQE/R4/benchmark/startQiskit_Class197.py", "benchmark/startQiskit1762.py", "benchmark/startQiskit_QC3235.py", "data/p4VQE/R1/benchmark/startQiskit_noisy94.py", "benchmark/startQiskit2205.py", "data/p2DJ/New/R2/benchmark/startQiskit_noisy61.py", "data/p3BR/R1/benchmark/startQiskit_QC429.py", "data/p3BR/R2/benchmark/startQiskit_Class254.py", "data/p2DJ/New/R2/benchmark/startQiskit_Class161.py", "benchmark/startQiskit_noisy2117.py", "benchmark/startQiskit_QC2298.py", "data/p4VQE/R4/benchmark/startQiskit_QC402.py", "benchmark/startQiskit_noisy1150.py", "benchmark/startQiskit_QC1236.py", "benchmark/startQiskit_QC2165.py", "data/p3BR/R2/benchmark/startQiskit_QC195.py", "benchmark/startQiskit2824.py", "benchmark/startQiskit3157.py", "benchmark/startQiskit2557.py", "benchmark/startQiskit_noisy1891.py", "benchmark/startQiskit_noisy1159.py", "benchmark/startQiskit_QC1930.py", "data/p3BR/R1/benchmark/startQiskit_Class374.py", "data/p3BR/R1/benchmark/startQiskit_noisy381.py", "data/p2DJ/New/program/qiskit/class/startQiskit_Class268.py", "data/p2DJ/New/program/qiskit/noisy/startQiskit_noisy291.py", "data/p3BR/R2/benchmark/startQiskit81.py", "data/p4VQE/R4/benchmark/startQiskit_QC730.py", "data/p2DJ/New/R2/benchmark/startQiskit_QC170.py", "benchmark/startQiskit_noisy2573.py", "data/p3BR/R2/benchmark/startQiskit_noisy387.py", "benchmark/startQiskit_Class2317.py", "data/p4VQE/R4/benchmark/startQiskit_noisy343.py", "benchmark/startQiskit_QC1221.py", "benchmark/startQiskit_QC1367.py", "benchmark/startQiskit_noisy1857.py" ]
[ "# qubit number=3\n# total number=60\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=57\n prog.cz(input_qubit[0],input_qubit[2]) # number=58\n prog.h(input_qubit[2]) # number=59\n prog.x(input_qubit[2]) # number=55\n prog.cx(input_qubit[0],input_qubit[2]) # number=56\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit289.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[0],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[3],input_qubit[0]) # number=37\n prog.z(input_qubit[3]) # number=38\n prog.cx(input_qubit[3],input_qubit[0]) # number=39\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=14\n prog.h(input_qubit[1]) # number=30\n prog.cz(input_qubit[2],input_qubit[0]) # number=15\n prog.h(input_qubit[0]) # number=16\n prog.cx(input_qubit[0],input_qubit[2]) # number=20\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=17\n prog.cx(input_qubit[0],input_qubit[2]) # number=23\n prog.x(input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.cx(input_qubit[0],input_qubit[2]) # number=19\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2375.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=84\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=70\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC456.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=33\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.rx(-3.1101767270538954,input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=26\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[3]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=30\n prog.cz(input_qubit[3],input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=32\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.z(input_qubit[3]) # number=24\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[3]) # number=28\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2296.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.y(input_qubit[3]) # number=8\n prog.y(input_qubit[3]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy62.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.z(input_qubit[3]) # number=24\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2042.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=42\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=35\n prog.cz(input_qubit[0],input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.z(input_qubit[1]) # number=24\n prog.h(input_qubit[2]) # number=39\n prog.cz(input_qubit[3],input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=41\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.8902652413026093,input_qubit[2]) # number=13\n\n prog.y(input_qubit[1]) # number=11\n prog.y(input_qubit[1]) # number=12\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2925.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=36\n prog.cz(input_qubit[0],input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=32\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.z(input_qubit[3]) # number=27\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2285.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=15\n prog.cz(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[1]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=23\n prog.cz(input_qubit[2],input_qubit[0]) # number=24\n prog.h(input_qubit[0]) # number=25\n prog.y(input_qubit[2]) # number=30\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.cx(input_qubit[2],input_qubit[0]) # number=18\n prog.h(input_qubit[0]) # number=26\n prog.x(input_qubit[2]) # number=31\n prog.cz(input_qubit[2],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2348.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=9\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.x(input_qubit[1]) # number=2\n prog.x(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class124.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=13\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[0]) # number=8\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.x(input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class182.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=15\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.h(input_qubit[2]) # number=12\n prog.cz(input_qubit[0],input_qubit[2]) # number=13\n prog.h(input_qubit[2]) # number=14\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC277.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=49\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.cx(input_qubit[0],input_qubit[3]) # number=40\n prog.x(input_qubit[3]) # number=41\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.33300882128051834,input_qubit[2]) # number=36\n prog.h(input_qubit[0]) # number=35\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=46\n prog.z(input_qubit[3]) # number=47\n prog.cx(input_qubit[3],input_qubit[0]) # number=48\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3343.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=44\n prog.cz(input_qubit[3],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=47\n prog.z(input_qubit[3]) # number=48\n prog.cx(input_qubit[3],input_qubit[0]) # number=49\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.11938052083641225,input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(1.4765485471872026,input_qubit[2]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.x(input_qubit[4]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(0.45238934211692994,input_qubit[3]) # number=38\n prog.y(input_qubit[1]) # number=39\n prog.rx(-2.5258404934861938,input_qubit[1]) # number=25\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=24\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(-0.0722566310325653,input_qubit[4]) # number=37\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[2]) # number=26\n prog.x(input_qubit[2]) # number=27\n prog.h(input_qubit[4]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1590.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=18\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.rx(2.0860175219836226,input_qubit[1]) # number=7\n prog.x(input_qubit[0]) # number=5\n prog.x(input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n prog.x(input_qubit[1]) # number=16\n prog.x(input_qubit[1]) # number=17\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit336.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[0],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[1]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.swap(input_qubit[3],input_qubit[0]) # number=22\n prog.swap(input_qubit[3],input_qubit[0]) # number=23\n prog.swap(input_qubit[1],input_qubit[0]) # number=27\n prog.swap(input_qubit[1],input_qubit[0]) # number=28\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2320.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=7\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[2]) # number=2\n prog.cx(input_qubit[2],input_qubit[1]) # number=4\n prog.z(input_qubit[2]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy43.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[2]) # number=5\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC77.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=42\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=39\n prog.cz(input_qubit[3],input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=33\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.11938052083641225,input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(1.4765485471872026,input_qubit[2]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[4]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(0.45238934211692994,input_qubit[3]) # number=38\n prog.rx(-2.5258404934861938,input_qubit[1]) # number=25\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=24\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(-0.0722566310325653,input_qubit[4]) # number=37\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[2]) # number=26\n prog.x(input_qubit[2]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1126.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=41\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=35\n prog.cz(input_qubit[0],input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[3],input_qubit[0]) # number=38\n prog.z(input_qubit[3]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=40\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.z(input_qubit[1]) # number=24\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.8902652413026093,input_qubit[2]) # number=13\n\n prog.y(input_qubit[1]) # number=11\n prog.y(input_qubit[1]) # number=12\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2660.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.cx(input_qubit[3],input_qubit[0]) # number=8\n prog.z(input_qubit[3]) # number=9\n prog.cx(input_qubit[3],input_qubit[0]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[3],input_qubit[0]) # number=5\n prog.swap(input_qubit[3],input_qubit[0]) # number=6\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit92.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=73\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=70\n prog.cz(input_qubit[0],input_qubit[2]) # number=71\n prog.h(input_qubit[2]) # number=72\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class364.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=10\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.cx(input_qubit[0],input_qubit[1]) # number=7\n prog.x(input_qubit[1]) # number=8\n prog.cx(input_qubit[0],input_qubit[1]) # number=9\n prog.x(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class143.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.y(input_qubit[2]) # number=18\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[3],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.z(input_qubit[3]) # number=41\n prog.cx(input_qubit[3],input_qubit[0]) # number=42\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[2],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[1]) # number=19\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[2],input_qubit[0]) # number=16\n prog.h(input_qubit[0]) # number=17\n prog.rx(1.6838936623241292,input_qubit[2]) # number=36\n prog.y(input_qubit[1]) # number=26\n prog.y(input_qubit[1]) # number=27\n prog.swap(input_qubit[1],input_qubit[0]) # number=29\n prog.swap(input_qubit[1],input_qubit[0]) # number=30\n prog.x(input_qubit[0]) # number=31\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.x(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=39\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3399.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=49\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.cx(input_qubit[0],input_qubit[3]) # number=40\n prog.cx(input_qubit[0],input_qubit[3]) # number=46\n prog.x(input_qubit[3]) # number=47\n prog.cx(input_qubit[0],input_qubit[3]) # number=48\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.33300882128051834,input_qubit[2]) # number=36\n prog.h(input_qubit[0]) # number=35\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.z(input_qubit[3]) # number=24\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy3345.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=13\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=8\n prog.cz(input_qubit[0],input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[1]) # number=5\n prog.cx(input_qubit[0],input_qubit[1]) # number=7\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[0]) # number=3\n prog.y(input_qubit[1]) # number=6\n prog.x(input_qubit[0]) # number=4\n prog.x(input_qubit[1]) # number=11\n prog.x(input_qubit[1]) # number=12\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit250.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=69\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[4],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.z(input_qubit[4]) # number=55\n prog.cx(input_qubit[4],input_qubit[0]) # number=56\n prog.h(input_qubit[2]) # number=50\n prog.cz(input_qubit[4],input_qubit[2]) # number=51\n prog.h(input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=66\n prog.cz(input_qubit[3],input_qubit[0]) # number=67\n prog.h(input_qubit[0]) # number=68\n prog.z(input_qubit[3]) # number=61\n prog.cx(input_qubit[3],input_qubit[0]) # number=62\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[1],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=63\n prog.cz(input_qubit[1],input_qubit[0]) # number=64\n prog.h(input_qubit[0]) # number=65\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.y(input_qubit[2]) # number=41\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.rx(1.0398671683382215,input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1883.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=47\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.rx(-0.9927432785343745,input_qubit[1]) # number=43\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.cx(input_qubit[2],input_qubit[0]) # number=37\n prog.cx(input_qubit[2],input_qubit[0]) # number=44\n prog.z(input_qubit[2]) # number=45\n prog.cx(input_qubit[2],input_qubit[0]) # number=46\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cz(input_qubit[2],input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy3210.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=73\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class408.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.x(input_qubit[1]) # number=41\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.cx(input_qubit[1],input_qubit[0]) # number=51\n prog.x(input_qubit[0]) # number=52\n prog.cx(input_qubit[1],input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1314.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=10\n prog.x(input_qubit[1]) # number=11\n prog.cx(input_qubit[0],input_qubit[1]) # number=12\n prog.x(input_qubit[1]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC575.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=55\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.cx(input_qubit[0],input_qubit[1]) # number=52\n prog.x(input_qubit[1]) # number=53\n prog.cx(input_qubit[0],input_qubit[1]) # number=54\n prog.h(input_qubit[1]) # number=26\n prog.cz(input_qubit[4],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=28\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[4],input_qubit[1]) # number=35\n prog.z(input_qubit[4]) # number=46\n prog.rx(0.8011061266653969,input_qubit[2]) # number=37\n prog.h(input_qubit[1]) # number=36\n prog.z(input_qubit[3]) # number=51\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.rx(-1.928937889304133,input_qubit[2]) # number=49\n prog.x(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=44\n prog.x(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=45\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=41\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[4]) # number=47\n prog.x(input_qubit[0]) # number=23\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[2]) # number=15\n prog.h(input_qubit[4]) # number=29\n prog.x(input_qubit[3]) # number=16\n prog.z(input_qubit[3]) # number=50\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1911.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=16\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n prog.x(input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class230.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=70\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[1]) # number=29\n prog.cz(input_qubit[3],input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=31\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[0]) # number=64\n prog.cz(input_qubit[1],input_qubit[0]) # number=65\n prog.h(input_qubit[0]) # number=66\n prog.x(input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[1],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[1],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.h(input_qubit[4]) # number=41\n prog.h(input_qubit[0]) # number=61\n prog.cz(input_qubit[1],input_qubit[0]) # number=62\n prog.h(input_qubit[0]) # number=63\n prog.cx(input_qubit[0],input_qubit[1]) # number=67\n prog.x(input_qubit[1]) # number=68\n prog.cx(input_qubit[0],input_qubit[1]) # number=69\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=42\n prog.cz(input_qubit[0],input_qubit[3]) # number=43\n prog.h(input_qubit[3]) # number=44\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(0.6157521601035993,input_qubit[1]) # number=60\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1786.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy116.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=59\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[1],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.z(input_qubit[1]) # number=37\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=56\n prog.cz(input_qubit[3],input_qubit[0]) # number=57\n prog.h(input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=47\n prog.x(input_qubit[4]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=44\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[4],input_qubit[3]) # number=54\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.y(input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[4],input_qubit[3]) # number=55\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1740.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.cx(input_qubit[2],input_qubit[1]) # number=27\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=24\n prog.cz(input_qubit[3],input_qubit[0]) # number=25\n prog.h(input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[3],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.z(input_qubit[3]) # number=29\n prog.cx(input_qubit[3],input_qubit[0]) # number=30\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2002.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=10\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=5\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.x(input_qubit[0]) # number=3\n prog.y(input_qubit[1]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class145.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=31\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.cx(input_qubit[2],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class179.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=69\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[4],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.z(input_qubit[4]) # number=55\n prog.cx(input_qubit[4],input_qubit[0]) # number=56\n prog.h(input_qubit[2]) # number=50\n prog.cz(input_qubit[4],input_qubit[2]) # number=51\n prog.h(input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=66\n prog.cz(input_qubit[3],input_qubit[0]) # number=67\n prog.h(input_qubit[0]) # number=68\n prog.z(input_qubit[3]) # number=61\n prog.cx(input_qubit[3],input_qubit[0]) # number=62\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[1],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=63\n prog.cz(input_qubit[1],input_qubit[0]) # number=64\n prog.h(input_qubit[0]) # number=65\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.y(input_qubit[2]) # number=41\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.rx(1.0398671683382215,input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1883.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=9\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[1]) # number=5\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.cx(input_qubit[0],input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=8\n prog.x(input_qubit[1]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC79.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=7\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.swap(input_qubit[1],input_qubit[0]) # number=5\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit78.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=9\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[1]) # number=2\n prog.x(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[1]) # number=7\n prog.y(input_qubit[1]) # number=8\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy126.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=43\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.cx(input_qubit[2],input_qubit[0]) # number=37\n prog.cx(input_qubit[2],input_qubit[0]) # number=40\n prog.z(input_qubit[2]) # number=41\n prog.cx(input_qubit[2],input_qubit[0]) # number=42\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.cx(input_qubit[2],input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2692.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=28\n prog.cz(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=15\n prog.rx(1.8001325905069514,input_qubit[3]) # number=18\n prog.z(input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[1]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[1]) # number=21\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.x(input_qubit[1]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.y(input_qubit[0]) # number=12\n prog.y(input_qubit[0]) # number=13\n prog.z(input_qubit[2]) # number=26\n prog.cx(input_qubit[2],input_qubit[1]) # number=23\n prog.x(input_qubit[0]) # number=19\n prog.x(input_qubit[0]) # number=20\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit3377.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=83\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=70\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class446.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=45\n prog.cx(input_qubit[1],input_qubit[0]) # number=49\n prog.z(input_qubit[1]) # number=50\n prog.cx(input_qubit[1],input_qubit[0]) # number=51\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[4]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1162.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=21\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n prog.cx(input_qubit[1],input_qubit[0]) # number=18\n prog.x(input_qubit[0]) # number=19\n prog.cx(input_qubit[1],input_qubit[0]) # number=20\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n prog.x(input_qubit[0]) # number=16\n prog.x(input_qubit[0]) # number=17\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit350.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=28\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.x(input_qubit[3]) # number=1\n prog.rx(-1.9352210746113125,input_qubit[3]) # number=14\n prog.cx(input_qubit[1],input_qubit[2]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[2]) # number=13\n prog.rx(0.13823007675795101,input_qubit[2]) # number=24\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.rx(-1.9069467407290044,input_qubit[2]) # number=20\n prog.h(input_qubit[3]) # number=21\n\n prog.y(input_qubit[2]) # number=10\n prog.h(input_qubit[1]) # number=17\n prog.cz(input_qubit[3],input_qubit[1]) # number=18\n prog.h(input_qubit[1]) # number=19\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=15\n prog.cx(input_qubit[1],input_qubit[0]) # number=16\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.z(input_qubit[3]) # number=26\n prog.cx(input_qubit[3],input_qubit[0]) # number=27\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2209.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=73\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.cx(input_qubit[0],input_qubit[1]) # number=70\n prog.x(input_qubit[1]) # number=71\n prog.cx(input_qubit[0],input_qubit[1]) # number=72\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy360.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=56\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=50\n prog.cz(input_qubit[4],input_qubit[2]) # number=51\n prog.h(input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=53\n prog.z(input_qubit[3]) # number=54\n prog.cx(input_qubit[3],input_qubit[0]) # number=55\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[1],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.y(input_qubit[2]) # number=41\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.rx(1.0398671683382215,input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1309.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=30\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.x(input_qubit[3]) # number=15\n prog.rx(1.8001325905069514,input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[1]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n prog.cx(input_qubit[0],input_qubit[3]) # number=29\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[1]) # number=21\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.x(input_qubit[1]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.y(input_qubit[0]) # number=12\n prog.y(input_qubit[0]) # number=13\n prog.z(input_qubit[2]) # number=26\n prog.cx(input_qubit[2],input_qubit[1]) # number=23\n prog.x(input_qubit[0]) # number=19\n prog.x(input_qubit[0]) # number=20\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2602.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=38\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=35\n prog.cz(input_qubit[0],input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=37\n prog.x(input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.z(input_qubit[1]) # number=24\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.8902652413026093,input_qubit[2]) # number=13\n\n prog.y(input_qubit[1]) # number=11\n prog.y(input_qubit[1]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2396.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.y(input_qubit[2]) # number=9\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.y(input_qubit[2]) # number=7\n prog.y(input_qubit[2]) # number=8\n prog.y(input_qubit[0]) # number=10\n prog.y(input_qubit[0]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_Class295.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=56\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[1]) # number=52\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.x(input_qubit[1]) # number=41\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.cx(input_qubit[1],input_qubit[0]) # number=53\n prog.x(input_qubit[0]) # number=54\n prog.cx(input_qubit[1],input_qubit[0]) # number=55\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[3]) # number=51\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1550.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.x(input_qubit[1]) # number=41\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.x(input_qubit[0]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=49\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1088.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=45\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=32\n prog.cz(input_qubit[0],input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.cx(input_qubit[0],input_qubit[3]) # number=42\n prog.x(input_qubit[3]) # number=43\n prog.cx(input_qubit[0],input_qubit[3]) # number=44\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=29\n prog.cz(input_qubit[0],input_qubit[2]) # number=30\n prog.h(input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=21\n prog.h(input_qubit[2]) # number=39\n prog.cz(input_qubit[0],input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=41\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.y(input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=37\n prog.z(input_qubit[1]) # number=35\n prog.y(input_qubit[3]) # number=38\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[3],input_qubit[0]) # number=13\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3224.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=41\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=38\n prog.cz(input_qubit[0],input_qubit[3]) # number=39\n prog.h(input_qubit[3]) # number=40\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[2]) # number=36\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[2]) # number=37\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=13\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[1],input_qubit[0]) # number=16\n prog.h(input_qubit[1]) # number=20\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[3],input_qubit[0]) # number=24\n prog.z(input_qubit[3]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=21\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[2],input_qubit[0]) # number=22\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC3361.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=15\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=12\n prog.x(input_qubit[2]) # number=13\n prog.cx(input_qubit[0],input_qubit[2]) # number=14\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.h(input_qubit[1]) # number=11\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n prog.y(input_qubit[0]) # number=9\n prog.y(input_qubit[0]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC727.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=8\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[1]) # number=9\n prog.y(input_qubit[1]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC419.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=4\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC2.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=45\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=32\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.cx(input_qubit[0],input_qubit[1]) # number=26\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[0],input_qubit[2]) # number=42\n prog.x(input_qubit[2]) # number=43\n prog.cx(input_qubit[0],input_qubit[2]) # number=44\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1025.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.x(input_qubit[4]) # number=53\n prog.cx(input_qubit[2],input_qubit[0]) # number=45\n prog.cx(input_qubit[2],input_qubit[0]) # number=57\n prog.z(input_qubit[2]) # number=58\n prog.cx(input_qubit[2],input_qubit[0]) # number=59\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[2],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.h(input_qubit[1]) # number=4\n prog.rx(2.664070570244145,input_qubit[1]) # number=39\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[2]) # number=49\n prog.cz(input_qubit[3],input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=51\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[3]) # number=40\n prog.y(input_qubit[4]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.cx(input_qubit[2],input_qubit[3]) # number=44\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n prog.z(input_qubit[1]) # number=52\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1753.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=7\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.x(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.x(input_qubit[1]) # number=5\n prog.cx(input_qubit[0],input_qubit[1]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class25.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=29\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.x(input_qubit[3]) # number=15\n prog.rx(1.8001325905069514,input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[1]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.x(input_qubit[3]) # number=24\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.z(input_qubit[1]) # number=27\n prog.cx(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.x(input_qubit[1]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.y(input_qubit[0]) # number=12\n prog.y(input_qubit[0]) # number=13\n prog.cx(input_qubit[2],input_qubit[1]) # number=23\n prog.x(input_qubit[0]) # number=19\n prog.x(input_qubit[0]) # number=20\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2334.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=28\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.x(input_qubit[3]) # number=1\n prog.rx(-1.9352210746113125,input_qubit[3]) # number=14\n prog.cx(input_qubit[1],input_qubit[2]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[2]) # number=13\n prog.rx(0.13823007675795101,input_qubit[2]) # number=24\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.rx(-1.9069467407290044,input_qubit[2]) # number=20\n prog.h(input_qubit[3]) # number=21\n\n prog.y(input_qubit[2]) # number=10\n prog.h(input_qubit[1]) # number=17\n prog.cz(input_qubit[3],input_qubit[1]) # number=18\n prog.h(input_qubit[1]) # number=19\n prog.y(input_qubit[2]) # number=11\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.cx(input_qubit[1],input_qubit[0]) # number=16\n prog.z(input_qubit[3]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2212.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=20\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[2])) # number=15\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=14\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=17\n c.append(cirq.X.on(input_qubit[1])) # number=18\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=19\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=11\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=12\n c.append(cirq.H.on(input_qubit[0])) # number=13\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.CNOT.on(input_qubit[1],input_qubit[2])) # number=16\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =4000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class863.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=5\n# total number=57\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=54\n prog.z(input_qubit[1]) # number=55\n prog.cx(input_qubit[1],input_qubit[0]) # number=56\n prog.cx(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.x(input_qubit[3]) # number=46\n prog.y(input_qubit[1]) # number=47\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1493.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.cx(input_qubit[0],input_qubit[1]) # number=51\n prog.x(input_qubit[1]) # number=52\n prog.cx(input_qubit[0],input_qubit[1]) # number=53\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1321.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=26\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.x(input_qubit[3]) # number=15\n prog.rx(1.8001325905069514,input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[1]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.x(input_qubit[3]) # number=24\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[1]) # number=21\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.x(input_qubit[1]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.y(input_qubit[0]) # number=12\n prog.y(input_qubit[0]) # number=13\n prog.cx(input_qubit[2],input_qubit[1]) # number=23\n prog.x(input_qubit[0]) # number=19\n prog.x(input_qubit[0]) # number=20\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2071.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=21\n prog.cz(input_qubit[0],input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=27\n prog.cz(input_qubit[0],input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.rx(-0.364424747816416,input_qubit[3]) # number=36\n prog.y(input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=19\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2221.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=25\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=18\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=19\n c.append(cirq.H.on(input_qubit[0])) # number=20\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=22\n c.append(cirq.X.on(input_qubit[2])) # number=23\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=24\n c.append(cirq.H.on(input_qubit[0])) # number=10\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=11\n c.append(cirq.H.on(input_qubit[0])) # number=12\n c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=8\n c.append(cirq.H.on(input_qubit[0])) # number=13\n c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) # number=14\n c.append(cirq.H.on(input_qubit[0])) # number=15\n c.append(cirq.X.on(input_qubit[2])) # number=16\n c.append(cirq.X.on(input_qubit[2])) # number=17\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =0\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class840.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=3\n# total number=60\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=57\n prog.cz(input_qubit[0],input_qubit[2]) # number=58\n prog.h(input_qubit[2]) # number=59\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC292.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=8\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.rx(1.6147786239451536).on(input_qubit[3])) # number=5\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.X.on(input_qubit[1])) # number=6\n c.append(cirq.X.on(input_qubit[1])) # number=7\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class18.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=5\n# total number=45\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[1],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=39\n prog.cz(input_qubit[1],input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[1],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.x(input_qubit[2]) # number=26\n prog.cx(input_qubit[0],input_qubit[2]) # number=27\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[2],input_qubit[4]) # number=37\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit953.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=8\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=2\n prog.swap(input_qubit[1],input_qubit[0]) # number=3\n prog.x(input_qubit[1]) # number=5\n prog.z(input_qubit[1]) # number=4\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class137.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=32\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.x(input_qubit[3]) # number=14\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.cx(input_qubit[2],input_qubit[3]) # number=22\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=24\n prog.cz(input_qubit[3],input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=20\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1996.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=5\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[3]) # number=7\n prog.y(input_qubit[3]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_Class82.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.cx(input_qubit[4],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[4],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.z(input_qubit[4]) # number=34\n prog.cx(input_qubit[4],input_qubit[0]) # number=35\n prog.cx(input_qubit[4],input_qubit[0]) # number=32\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[1],input_qubit[2]) # number=39\n prog.h(input_qubit[3]) # number=8\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=26\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.y(input_qubit[2]) # number=29\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit843.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=14\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.cx(input_qubit[3],input_qubit[0]) # number=11\n prog.z(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[0]) # number=13\n prog.z(input_qubit[1]) # number=8\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[3],input_qubit[0]) # number=5\n prog.swap(input_qubit[3],input_qubit[0]) # number=6\n prog.x(input_qubit[3]) # number=9\n prog.x(input_qubit[3]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy696.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=45\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=42\n prog.cz(input_qubit[1],input_qubit[0]) # number=43\n prog.h(input_qubit[0]) # number=44\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.cx(input_qubit[0],input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=40\n prog.cx(input_qubit[0],input_qubit[1]) # number=41\n prog.cx(input_qubit[0],input_qubit[1]) # number=34\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=35\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.z(input_qubit[1]) # number=31\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1005.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=42\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=10\n prog.h(input_qubit[3]) # number=39\n prog.cz(input_qubit[0],input_qubit[3]) # number=40\n prog.h(input_qubit[3]) # number=41\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=21\n prog.h(input_qubit[2]) # number=36\n prog.cz(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=38\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[3],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n prog.y(input_qubit[2]) # number=29\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2449.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=16\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[2])) # number=15\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=14\n c.append(cirq.X.on(input_qubit[1])) # number=10\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=11\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=12\n c.append(cirq.H.on(input_qubit[0])) # number=13\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2820\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class485.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=3\n# total number=31\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[2]) # number=12\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit166.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=79\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=71\n prog.cz(input_qubit[0],input_qubit[2]) # number=72\n prog.h(input_qubit[2]) # number=73\n prog.cx(input_qubit[0],input_qubit[2]) # number=76\n prog.x(input_qubit[2]) # number=77\n prog.cx(input_qubit[0],input_qubit[2]) # number=78\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.x(input_qubit[2]) # number=74\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.cx(input_qubit[2],input_qubit[1]) # number=75\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.cx(input_qubit[2],input_qubit[1]) # number=70\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy401.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.z(input_qubit[3]) # number=27\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2024.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.x(input_qubit[3]) # number=1\n prog.h(input_qubit[0]) # number=18\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=34\n prog.cz(input_qubit[3],input_qubit[0]) # number=19\n prog.h(input_qubit[2]) # number=24\n prog.h(input_qubit[0]) # number=20\n prog.rx(-1.8378317023500288,input_qubit[1]) # number=25\n prog.z(input_qubit[3]) # number=14\n prog.cx(input_qubit[3],input_qubit[0]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[3]) # number=16\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[3]) # number=29\n prog.cz(input_qubit[0],input_qubit[3]) # number=30\n prog.h(input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.z(input_qubit[1]) # number=26\n\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[2]) # number=12\n prog.z(input_qubit[1]) # number=27\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2679.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=60\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC338.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.z(input_qubit[3]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.z(input_qubit[1]) # number=10\n prog.cx(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[2]) # number=3\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[3],input_qubit[0]) # number=5\n prog.swap(input_qubit[3],input_qubit[0]) # number=6\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy676.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=59\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy324.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=22\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC121.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.y(input_qubit[2]) # number=8\n prog.y(input_qubit[2]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy163.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=44\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.48380526865282825,input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.y(input_qubit[3]) # number=18\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[0],input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=36\n prog.h(input_qubit[1]) # number=41\n prog.cz(input_qubit[0],input_qubit[1]) # number=42\n prog.h(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=38\n prog.x(input_qubit[1]) # number=39\n prog.cx(input_qubit[0],input_qubit[1]) # number=40\n prog.cx(input_qubit[0],input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=37\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=22\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit3286.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=28\n prog.cz(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=15\n prog.rx(1.8001325905069514,input_qubit[3]) # number=18\n prog.z(input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[1]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[1]) # number=21\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.x(input_qubit[1]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.y(input_qubit[0]) # number=12\n prog.y(input_qubit[0]) # number=13\n prog.z(input_qubit[2]) # number=26\n prog.cx(input_qubit[2],input_qubit[1]) # number=23\n prog.x(input_qubit[0]) # number=19\n prog.x(input_qubit[0]) # number=20\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC3118.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=10\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.x(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=7\n prog.x(input_qubit[1]) # number=8\n prog.cx(input_qubit[0],input_qubit[1]) # number=9\n prog.swap(input_qubit[1],input_qubit[0]) # number=5\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class159.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=10\n prog.h(input_qubit[3]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2201.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.x(input_qubit[2]) # number=34\n prog.y(input_qubit[1]) # number=19\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.y(input_qubit[3]) # number=20\n prog.y(input_qubit[1]) # number=12\n prog.rx(-2.158274153016188,input_qubit[3]) # number=24\n prog.h(input_qubit[0]) # number=16\n prog.cz(input_qubit[2],input_qubit[0]) # number=17\n prog.h(input_qubit[0]) # number=18\n prog.cx(input_qubit[1],input_qubit[0]) # number=21\n prog.z(input_qubit[1]) # number=22\n prog.cx(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[2],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.x(input_qubit[0]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.x(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=39\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3016.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit252.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=44\n prog.cz(input_qubit[3],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=46\n prog.z(input_qubit[3]) # number=33\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.11938052083641225,input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(1.4765485471872026,input_qubit[2]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.x(input_qubit[4]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=47\n prog.x(input_qubit[1]) # number=48\n prog.cx(input_qubit[0],input_qubit[1]) # number=49\n prog.x(input_qubit[2]) # number=11\n prog.rx(0.45238934211692994,input_qubit[3]) # number=38\n prog.y(input_qubit[1]) # number=39\n prog.rx(-2.5258404934861938,input_qubit[1]) # number=25\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=24\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(-0.0722566310325653,input_qubit[4]) # number=37\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[2]) # number=26\n prog.x(input_qubit[2]) # number=27\n prog.h(input_qubit[4]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1591.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=10\n prog.cz(input_qubit[1],input_qubit[2]) # number=11\n prog.h(input_qubit[2]) # number=12\n prog.x(input_qubit[2]) # number=6\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_Class718.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=19\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.rx(2.0860175219836226,input_qubit[1]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=16\n prog.x(input_qubit[0]) # number=17\n prog.cx(input_qubit[1],input_qubit[0]) # number=18\n prog.x(input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit332.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=59\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[1]) # number=52\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.h(input_qubit[1]) # number=56\n prog.cz(input_qubit[0],input_qubit[1]) # number=57\n prog.h(input_qubit[1]) # number=58\n prog.x(input_qubit[1]) # number=54\n prog.cx(input_qubit[0],input_qubit[1]) # number=55\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[3]) # number=51\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1658.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=8\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.x(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy666.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=33\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=11\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1938.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=8\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[1]) # number=5\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.x(input_qubit[1]) # number=2\n prog.x(input_qubit[1]) # number=3\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class80.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n prog.x(input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit113.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=51\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.cx(input_qubit[2],input_qubit[0]) # number=45\n prog.cx(input_qubit[2],input_qubit[0]) # number=48\n prog.z(input_qubit[2]) # number=49\n prog.cx(input_qubit[2],input_qubit[0]) # number=50\n prog.cx(input_qubit[2],input_qubit[0]) # number=47\n prog.h(input_qubit[1]) # number=4\n prog.rx(2.664070570244145,input_qubit[1]) # number=39\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[3]) # number=40\n prog.y(input_qubit[4]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.cx(input_qubit[2],input_qubit[3]) # number=44\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1184.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=58\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.cx(input_qubit[1],input_qubit[0]) # number=52\n prog.cx(input_qubit[1],input_qubit[0]) # number=55\n prog.z(input_qubit[1]) # number=56\n prog.cx(input_qubit[1],input_qubit[0]) # number=57\n prog.cx(input_qubit[1],input_qubit[0]) # number=54\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[4]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1390.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=41\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.48380526865282825,input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.y(input_qubit[3]) # number=18\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[0],input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=36\n prog.h(input_qubit[1]) # number=38\n prog.cz(input_qubit[0],input_qubit[1]) # number=39\n prog.h(input_qubit[1]) # number=40\n prog.x(input_qubit[1]) # number=32\n prog.cx(input_qubit[0],input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=37\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=22\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit3021.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.y(input_qubit[2]) # number=7\n prog.y(input_qubit[2]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_Class54.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=21\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5\n c.append(cirq.H.on(input_qubit[0])) # number=16\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=17\n c.append(cirq.H.on(input_qubit[0])) # number=18\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=12\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=13\n c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=14\n c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=15\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=19\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=20\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2820\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class729.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.h(input_qubit[3]) # number=40\n prog.cz(input_qubit[0],input_qubit[3]) # number=41\n prog.h(input_qubit[3]) # number=42\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=21\n prog.h(input_qubit[2]) # number=36\n prog.cz(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=38\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[2]) # number=39\n\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[3],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n prog.y(input_qubit[2]) # number=29\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2970.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=14\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[1],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=6\n prog.y(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=11\n prog.cz(input_qubit[3],input_qubit[2]) # number=12\n prog.h(input_qubit[2]) # number=13\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_noisy740.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=42\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.cx(input_qubit[0],input_qubit[2]) # number=39\n prog.x(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=41\n prog.cx(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[2]) # number=36\n prog.cz(input_qubit[3],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=38\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=19\n prog.cz(input_qubit[2],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=21\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[2],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2629.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit457.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=17\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=12\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=13\n c.append(cirq.H.on(input_qubit[0])) # number=14\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11\n c.append(cirq.Y.on(input_qubit[1])) # number=15\n c.append(cirq.Y.on(input_qubit[1])) # number=16\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2820\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class366.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=3\n# total number=57\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.x(input_qubit[2]) # number=55\n prog.cx(input_qubit[0],input_qubit[2]) # number=56\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class273.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[1],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.z(input_qubit[1]) # number=37\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=47\n prog.x(input_qubit[4]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=44\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.y(input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1394.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.z(input_qubit[1]) # number=12\n prog.y(input_qubit[3]) # number=8\n prog.y(input_qubit[3]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_Class528.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=63\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy345.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=43\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=35\n prog.cz(input_qubit[0],input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.z(input_qubit[1]) # number=24\n prog.h(input_qubit[2]) # number=40\n prog.cz(input_qubit[3],input_qubit[2]) # number=41\n prog.h(input_qubit[2]) # number=42\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[3]) # number=39\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.8902652413026093,input_qubit[2]) # number=13\n\n prog.y(input_qubit[1]) # number=11\n prog.y(input_qubit[1]) # number=12\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy3179.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[2]) # number=8\n prog.x(input_qubit[2]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC162.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=62\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[1],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.z(input_qubit[1]) # number=37\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=56\n prog.cz(input_qubit[3],input_qubit[0]) # number=57\n prog.h(input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=46\n prog.h(input_qubit[0]) # number=59\n prog.cz(input_qubit[3],input_qubit[0]) # number=60\n prog.h(input_qubit[0]) # number=61\n prog.x(input_qubit[4]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=44\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[4],input_qubit[3]) # number=54\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.y(input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[4],input_qubit[3]) # number=55\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1857.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=69\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[4],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.cx(input_qubit[4],input_qubit[0]) # number=66\n prog.z(input_qubit[4]) # number=67\n prog.cx(input_qubit[4],input_qubit[0]) # number=68\n prog.cx(input_qubit[4],input_qubit[0]) # number=56\n prog.h(input_qubit[2]) # number=50\n prog.cz(input_qubit[4],input_qubit[2]) # number=51\n prog.h(input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=60\n prog.z(input_qubit[3]) # number=61\n prog.cx(input_qubit[3],input_qubit[0]) # number=62\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[1],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=63\n prog.cz(input_qubit[1],input_qubit[0]) # number=64\n prog.h(input_qubit[0]) # number=65\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.y(input_qubit[2]) # number=41\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.rx(1.0398671683382215,input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1879.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=43\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=40\n prog.cz(input_qubit[4],input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[4],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.z(input_qubit[4]) # number=34\n prog.cx(input_qubit[4],input_qubit[0]) # number=35\n prog.cx(input_qubit[4],input_qubit[0]) # number=32\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[1],input_qubit[2]) # number=39\n prog.h(input_qubit[3]) # number=8\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=26\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.y(input_qubit[2]) # number=29\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class992.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=18\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.Z.on(input_qubit[3])) # number=14\n c.append(cirq.H.on(input_qubit[1])) # number=15\n c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=16\n c.append(cirq.H.on(input_qubit[1])) # number=17\n c.append(cirq.X.on(input_qubit[1])) # number=11\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=12\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.rx(2.808583832309275).on(input_qubit[2])) # number=7\n c.append(cirq.Y.on(input_qubit[3])) # number=13\n c.append(cirq.CNOT.on(input_qubit[1],input_qubit[3])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=5\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=6\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class796.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=5\n# total number=49\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.z(input_qubit[1]) # number=30\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[3],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1033.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[2]) # number=8\n prog.y(input_qubit[2]) # number=9\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.cx(input_qubit[1],input_qubit[0]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_noisy558.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=41\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.y(input_qubit[1]) # number=37\n prog.h(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[3],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.z(input_qubit[3]) # number=27\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[2]) # number=36\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2808.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=44\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=41\n prog.x(input_qubit[3]) # number=42\n prog.cx(input_qubit[0],input_qubit[3]) # number=43\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[0],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[3],input_qubit[0]) # number=38\n prog.z(input_qubit[3]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=40\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.y(input_qubit[3]) # number=37\n prog.h(input_qubit[0]) # number=14\n prog.h(input_qubit[1]) # number=30\n prog.cz(input_qubit[2],input_qubit[0]) # number=15\n prog.h(input_qubit[0]) # number=16\n prog.cx(input_qubit[0],input_qubit[2]) # number=20\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=17\n prog.cx(input_qubit[0],input_qubit[2]) # number=23\n prog.x(input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.cx(input_qubit[0],input_qubit[2]) # number=19\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2896.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=38\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=15\n prog.cz(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[3]) # number=17\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.z(input_qubit[3]) # number=33\n prog.h(input_qubit[0]) # number=5\n prog.x(input_qubit[3]) # number=32\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[1]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=23\n prog.rx(0.6063273821428302,input_qubit[3]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=24\n prog.h(input_qubit[0]) # number=25\n prog.y(input_qubit[2]) # number=30\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.cx(input_qubit[2],input_qubit[0]) # number=18\n prog.h(input_qubit[0]) # number=26\n prog.x(input_qubit[2]) # number=31\n prog.cz(input_qubit[2],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2868.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=53\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.x(input_qubit[1]) # number=48\n prog.h(input_qubit[1]) # number=26\n prog.cz(input_qubit[4],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=28\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[4],input_qubit[1]) # number=35\n prog.z(input_qubit[4]) # number=46\n prog.rx(0.8011061266653969,input_qubit[2]) # number=37\n prog.h(input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=50\n prog.cz(input_qubit[1],input_qubit[0]) # number=51\n prog.h(input_qubit[0]) # number=52\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.rx(-1.928937889304133,input_qubit[2]) # number=49\n prog.x(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=44\n prog.x(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=45\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=41\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[4]) # number=47\n prog.x(input_qubit[0]) # number=23\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[2]) # number=15\n prog.h(input_qubit[4]) # number=29\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1686.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.cx(input_qubit[2],input_qubit[0]) # number=45\n prog.z(input_qubit[2]) # number=46\n prog.cx(input_qubit[2],input_qubit[0]) # number=47\n prog.h(input_qubit[1]) # number=4\n prog.rx(2.664070570244145,input_qubit[1]) # number=39\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.cx(input_qubit[3],input_qubit[2]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[3]) # number=40\n prog.y(input_qubit[4]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=49\n prog.x(input_qubit[0]) # number=50\n prog.cx(input_qubit[1],input_qubit[0]) # number=51\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.cx(input_qubit[2],input_qubit[3]) # number=44\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1292.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=44\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.cx(input_qubit[0],input_qubit[2]) # number=35\n prog.x(input_qubit[2]) # number=36\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.cx(input_qubit[2],input_qubit[0]) # number=41\n prog.z(input_qubit[2]) # number=42\n prog.cx(input_qubit[2],input_qubit[0]) # number=43\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit228.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=57\n prog.x(input_qubit[0]) # number=58\n prog.cx(input_qubit[1],input_qubit[0]) # number=59\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.h(input_qubit[1]) # number=50\n prog.cz(input_qubit[0],input_qubit[1]) # number=51\n prog.h(input_qubit[1]) # number=52\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=42\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(1.7844246272390027,input_qubit[4]) # number=56\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[4]) # number=46\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=53\n prog.cz(input_qubit[0],input_qubit[2]) # number=54\n prog.h(input_qubit[2]) # number=55\n prog.x(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=47\n prog.cz(input_qubit[0],input_qubit[2]) # number=48\n prog.h(input_qubit[2]) # number=49\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1827.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=8\n prog.cz(input_qubit[1],input_qubit[0]) # number=9\n prog.h(input_qubit[0]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_Class107.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=44\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.rx(-3.1101767270538954,input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=26\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.cx(input_qubit[0],input_qubit[3]) # number=41\n prog.x(input_qubit[3]) # number=42\n prog.cx(input_qubit[0],input_qubit[3]) # number=43\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[3],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.z(input_qubit[3]) # number=24\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[3],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n prog.z(input_qubit[3]) # number=36\n prog.cx(input_qubit[3],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3334.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=65\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=62\n prog.cz(input_qubit[0],input_qubit[2]) # number=63\n prog.h(input_qubit[2]) # number=64\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy320.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=16\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.rx(2.0860175219836226,input_qubit[1]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=13\n prog.x(input_qubit[0]) # number=14\n prog.cx(input_qubit[1],input_qubit[0]) # number=15\n prog.x(input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy267.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[1]) # number=26\n prog.cz(input_qubit[4],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=28\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[4],input_qubit[1]) # number=35\n prog.z(input_qubit[4]) # number=46\n prog.rx(0.8011061266653969,input_qubit[2]) # number=37\n prog.h(input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.x(input_qubit[0]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=49\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.x(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=44\n prog.x(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=45\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=41\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[0]) # number=23\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[2]) # number=15\n prog.h(input_qubit[4]) # number=29\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1342.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=48\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.x(input_qubit[2]) # number=36\n prog.h(input_qubit[2]) # number=45\n prog.cz(input_qubit[0],input_qubit[2]) # number=46\n prog.h(input_qubit[2]) # number=47\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class245.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=44\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.rx(-0.9927432785343745,input_qubit[1]) # number=43\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.cx(input_qubit[2],input_qubit[0]) # number=37\n prog.z(input_qubit[2]) # number=38\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cz(input_qubit[2],input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2948.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=21\n prog.cz(input_qubit[0],input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=27\n prog.cz(input_qubit[0],input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.cx(input_qubit[0],input_qubit[3]) # number=40\n prog.cx(input_qubit[0],input_qubit[3]) # number=43\n prog.x(input_qubit[3]) # number=44\n prog.cx(input_qubit[0],input_qubit[3]) # number=45\n prog.cx(input_qubit[0],input_qubit[3]) # number=42\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.rx(-0.364424747816416,input_qubit[3]) # number=36\n prog.y(input_qubit[3]) # number=20\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=19\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2748.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n prog.x(input_qubit[2]) # number=8\n prog.x(input_qubit[2]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_noisy127.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=17\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=14\n c.append(cirq.X.on(input_qubit[1])) # number=15\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=16\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.rx(2.3027874150813186).on(input_qubit[1])) # number=13\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=11\n c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=12\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2580\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class505.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=4\n# total number=32\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.rx(-3.1101767270538954,input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=26\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.z(input_qubit[3]) # number=24\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[3]) # number=28\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2033.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy346.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=2\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC0.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=9\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[1]) # number=5\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=8\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC81.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=37\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.cx(input_qubit[1],input_qubit[0]) # number=31\n prog.x(input_qubit[0]) # number=32\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[2],input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=36\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=23\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.cx(input_qubit[1],input_qubit[3]) # number=27\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC604.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=4\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[0]) # number=2\n prog.x(input_qubit[0]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit7.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=49\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=45\n prog.z(input_qubit[1]) # number=46\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[4]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1039.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[1]) # number=31\n prog.cz(input_qubit[2],input_qubit[1]) # number=32\n prog.h(input_qubit[1]) # number=33\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=24\n prog.cz(input_qubit[3],input_qubit[0]) # number=25\n prog.h(input_qubit[0]) # number=26\n prog.cx(input_qubit[3],input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=37\n prog.z(input_qubit[3]) # number=38\n prog.cx(input_qubit[3],input_qubit[0]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=30\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2783.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_Class63.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=8\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=2\n prog.swap(input_qubit[1],input_qubit[0]) # number=3\n prog.x(input_qubit[1]) # number=5\n prog.z(input_qubit[1]) # number=4\n prog.x(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC133.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=31\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[2]) # number=12\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC167.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=12\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.cx(input_qubit[0],input_qubit[1]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[1]) # number=11\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.cx(input_qubit[0],input_qubit[1]) # number=7\n prog.x(input_qubit[1]) # number=8\n prog.x(input_qubit[1]) # number=5\n prog.cx(input_qubit[0],input_qubit[1]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy184.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=30\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.x(input_qubit[3]) # number=1\n prog.rx(-1.9352210746113125,input_qubit[3]) # number=14\n prog.cx(input_qubit[1],input_qubit[2]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[2]) # number=13\n prog.rx(0.13823007675795101,input_qubit[2]) # number=24\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.rx(-1.9069467407290044,input_qubit[2]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=27\n\n prog.y(input_qubit[2]) # number=10\n prog.h(input_qubit[1]) # number=17\n prog.cz(input_qubit[3],input_qubit[1]) # number=18\n prog.h(input_qubit[1]) # number=19\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=15\n prog.cx(input_qubit[1],input_qubit[0]) # number=16\n prog.z(input_qubit[3]) # number=23\n prog.y(input_qubit[1]) # number=25\n prog.y(input_qubit[1]) # number=26\n prog.y(input_qubit[0]) # number=28\n prog.y(input_qubit[0]) # number=29\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2733.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=28\n prog.cz(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=30\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.rx(2.708052867394402,input_qubit[1]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[2]) # number=16\n prog.cx(input_qubit[1],input_qubit[0]) # number=19\n prog.h(input_qubit[3]) # number=25\n prog.z(input_qubit[1]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=36\n prog.z(input_qubit[3]) # number=37\n prog.cx(input_qubit[3],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=22\n prog.cz(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=24\n prog.z(input_qubit[2]) # number=15\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.y(input_qubit[2]) # number=18\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[2]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC3166.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=6\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=2\n prog.swap(input_qubit[1],input_qubit[0]) # number=3\n prog.x(input_qubit[1]) # number=5\n prog.z(input_qubit[1]) # number=4\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC87.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=8\n prog.cz(input_qubit[1],input_qubit[0]) # number=9\n prog.h(input_qubit[0]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_noisy107.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.rx(2.9845130209103035,input_qubit[2]) # number=7\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.rx(1.6807520696705391,input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_noisy236.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.x(input_qubit[3]) # number=14\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.cx(input_qubit[2],input_qubit[3]) # number=22\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=24\n prog.cz(input_qubit[3],input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[0],input_qubit[2]) # number=29\n prog.x(input_qubit[2]) # number=30\n prog.h(input_qubit[2]) # number=32\n prog.cz(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=34\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=21\n prog.x(input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2248.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=15\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n prog.cx(input_qubit[1],input_qubit[3]) # number=12\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n prog.y(input_qubit[3]) # number=13\n prog.y(input_qubit[3]) # number=14\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_noisy494.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[2]) # number=8\n prog.x(input_qubit[2]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_noisy63.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=47\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=32\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.cx(input_qubit[0],input_qubit[1]) # number=26\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=42\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[4]) # number=46\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[0],input_qubit[2]) # number=43\n prog.x(input_qubit[2]) # number=44\n prog.cx(input_qubit[0],input_qubit[2]) # number=45\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1249.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=51\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC280.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=19\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy115.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=37\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[4]) # number=27\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=34\n prog.x(input_qubit[2]) # number=35\n prog.cx(input_qubit[0],input_qubit[2]) # number=36\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.y(input_qubit[1]) # number=26\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[2]) # number=31\n prog.cz(input_qubit[4],input_qubit[2]) # number=32\n prog.h(input_qubit[2]) # number=33\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class636.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=63\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.y(input_qubit[1]) # number=56\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[1]) # number=52\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.h(input_qubit[1]) # number=57\n prog.cz(input_qubit[0],input_qubit[1]) # number=58\n prog.h(input_qubit[1]) # number=59\n prog.x(input_qubit[1]) # number=54\n prog.h(input_qubit[1]) # number=60\n prog.cz(input_qubit[0],input_qubit[1]) # number=61\n prog.h(input_qubit[1]) # number=62\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[3]) # number=51\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1895.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[1]) # number=29\n prog.cz(input_qubit[3],input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=31\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=57\n prog.x(input_qubit[0]) # number=58\n prog.cx(input_qubit[1],input_qubit[0]) # number=59\n prog.cx(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[1],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.h(input_qubit[4]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.x(input_qubit[1]) # number=10\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=42\n prog.cz(input_qubit[0],input_qubit[3]) # number=43\n prog.h(input_qubit[3]) # number=44\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1324.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=14\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[1],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=6\n prog.y(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=11\n prog.cz(input_qubit[3],input_qubit[2]) # number=12\n prog.h(input_qubit[2]) # number=13\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC743.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=8\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[3]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit409.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=7\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.swap(input_qubit[1],input_qubit[0]) # number=5\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC78.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[4],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[4],input_qubit[0]) # number=46\n prog.z(input_qubit[4]) # number=47\n prog.cx(input_qubit[4],input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[4],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(-1.0430087609918113,input_qubit[4]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.x(input_qubit[0]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=42\n prog.x(input_qubit[1]) # number=10\n prog.rx(-0.06597344572538572,input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.h(input_qubit[4]) # number=35\n\n\n prog.h(input_qubit[0]) # number=17\n prog.rx(2.4912829742967055,input_qubit[2]) # number=26\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1348.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=6\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=5\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[0]) # number=3\n prog.x(input_qubit[0]) # number=4\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit55.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=36\n prog.cz(input_qubit[0],input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=38\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=28\n prog.cz(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=30\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.rx(2.708052867394402,input_qubit[1]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[2]) # number=16\n prog.cx(input_qubit[1],input_qubit[0]) # number=19\n prog.h(input_qubit[3]) # number=25\n prog.z(input_qubit[1]) # number=20\n prog.z(input_qubit[3]) # number=31\n prog.h(input_qubit[0]) # number=22\n prog.cz(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=24\n prog.z(input_qubit[2]) # number=15\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.y(input_qubit[2]) # number=18\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[2]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3168.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=47\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.rx(-0.9927432785343745,input_qubit[1]) # number=43\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.h(input_qubit[0]) # number=44\n prog.cz(input_qubit[2],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=46\n prog.z(input_qubit[2]) # number=38\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cz(input_qubit[2],input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3207.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[1]) # number=31\n prog.cz(input_qubit[2],input_qubit[1]) # number=32\n prog.h(input_qubit[1]) # number=33\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=24\n prog.cz(input_qubit[3],input_qubit[0]) # number=25\n prog.h(input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[3],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.z(input_qubit[3]) # number=29\n prog.cx(input_qubit[3],input_qubit[0]) # number=30\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2261.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=74\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=71\n prog.cz(input_qubit[0],input_qubit[2]) # number=72\n prog.h(input_qubit[2]) # number=73\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.cx(input_qubit[2],input_qubit[1]) # number=70\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class376.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[1],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=51\n prog.z(input_qubit[1]) # number=52\n prog.cx(input_qubit[1],input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=47\n prog.x(input_qubit[4]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=44\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.y(input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1400.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.cx(input_qubit[2],input_qubit[1]) # number=27\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=24\n prog.cz(input_qubit[3],input_qubit[0]) # number=25\n prog.h(input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[3],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.z(input_qubit[3]) # number=29\n prog.cx(input_qubit[3],input_qubit[0]) # number=30\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2007.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=31\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.48380526865282825,input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.y(input_qubit[3]) # number=18\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=28\n prog.x(input_qubit[1]) # number=29\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=22\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1981.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.x(input_qubit[1]) # number=48\n prog.h(input_qubit[1]) # number=26\n prog.cz(input_qubit[4],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=28\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[4],input_qubit[1]) # number=35\n prog.z(input_qubit[4]) # number=46\n prog.rx(0.8011061266653969,input_qubit[2]) # number=37\n prog.h(input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.rx(-1.928937889304133,input_qubit[2]) # number=49\n prog.x(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=44\n prog.x(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=45\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=41\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[4]) # number=47\n prog.x(input_qubit[0]) # number=23\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[2]) # number=15\n prog.h(input_qubit[4]) # number=29\n prog.x(input_qubit[3]) # number=16\n prog.z(input_qubit[3]) # number=50\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1797.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=42\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[1]) # number=39\n prog.cz(input_qubit[0],input_qubit[1]) # number=40\n prog.h(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=34\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=35\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.z(input_qubit[1]) # number=31\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy861.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=14\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11\n c.append(cirq.X.on(input_qubit[1])) # number=12\n c.append(cirq.X.on(input_qubit[1])) # number=13\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2820\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class240.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=5\n# total number=57\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.z(input_qubit[4]) # number=53\n prog.h(input_qubit[2]) # number=50\n prog.cz(input_qubit[4],input_qubit[2]) # number=51\n prog.h(input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.z(input_qubit[3]) # number=42\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[1],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[1],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.y(input_qubit[2]) # number=41\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.rx(1.0398671683382215,input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1424.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=9\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=7\n c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=8\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class26.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[1]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[1]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[3]) # number=7\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_Class656.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.48380526865282825,input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.y(input_qubit[3]) # number=18\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=28\n prog.x(input_qubit[1]) # number=29\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=22\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2242.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=15\n prog.cz(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.x(input_qubit[3]) # number=32\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[1]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=23\n prog.cz(input_qubit[2],input_qubit[0]) # number=24\n prog.h(input_qubit[0]) # number=25\n prog.y(input_qubit[2]) # number=30\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.cx(input_qubit[2],input_qubit[0]) # number=18\n prog.h(input_qubit[0]) # number=26\n prog.x(input_qubit[2]) # number=31\n prog.cz(input_qubit[2],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.swap(input_qubit[3],input_qubit[0]) # number=33\n prog.swap(input_qubit[3],input_qubit[0]) # number=34\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2350.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=16\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[1]) # number=15\n prog.cx(input_qubit[0],input_qubit[1]) # number=10\n prog.x(input_qubit[1]) # number=11\n prog.cx(input_qubit[0],input_qubit[1]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_Class585.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.y(input_qubit[1]) # number=56\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[1]) # number=52\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.h(input_qubit[1]) # number=57\n prog.cz(input_qubit[0],input_qubit[1]) # number=58\n prog.h(input_qubit[1]) # number=59\n prog.x(input_qubit[1]) # number=54\n prog.cx(input_qubit[0],input_qubit[1]) # number=55\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[3]) # number=51\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1773.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=38\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.cx(input_qubit[0],input_qubit[2]) # number=35\n prog.x(input_qubit[2]) # number=36\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=31\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=28\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.x(input_qubit[2]) # number=26\n prog.cx(input_qubit[0],input_qubit[2]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.rx(1.7404423300887455,input_qubit[1]) # number=32\n prog.z(input_qubit[1]) # number=33\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit873.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=73\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class410.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_noisy132.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=16\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[1]) # number=8\n prog.cx(input_qubit[0],input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[1]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[1]) # number=15\n prog.cx(input_qubit[0],input_qubit[1]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_noisy600.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=22\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy118.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=66\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[4],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.z(input_qubit[4]) # number=55\n prog.cx(input_qubit[4],input_qubit[0]) # number=56\n prog.h(input_qubit[2]) # number=50\n prog.cz(input_qubit[4],input_qubit[2]) # number=51\n prog.h(input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=63\n prog.cz(input_qubit[3],input_qubit[0]) # number=64\n prog.h(input_qubit[0]) # number=65\n prog.z(input_qubit[3]) # number=61\n prog.cx(input_qubit[3],input_qubit[0]) # number=62\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[1],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.y(input_qubit[2]) # number=41\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.rx(1.0398671683382215,input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1762.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=28\n prog.cx(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[2]) # number=33\n prog.cz(input_qubit[3],input_qubit[2]) # number=34\n prog.h(input_qubit[2]) # number=35\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=19\n prog.cz(input_qubit[2],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=21\n prog.cx(input_qubit[2],input_qubit[3]) # number=15\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2104.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=13\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class180.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=44\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.y(input_qubit[2]) # number=36\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.cx(input_qubit[3],input_qubit[1]) # number=35\n prog.y(input_qubit[2]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=22\n prog.cz(input_qubit[0],input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=18\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.cx(input_qubit[2],input_qubit[0]) # number=41\n prog.z(input_qubit[2]) # number=42\n prog.cx(input_qubit[2],input_qubit[0]) # number=43\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.cx(input_qubit[3],input_qubit[0]) # number=31\n prog.cx(input_qubit[3],input_qubit[0]) # number=37\n prog.z(input_qubit[3]) # number=38\n prog.cx(input_qubit[3],input_qubit[0]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3188.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=38\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[3]) # number=35\n prog.cz(input_qubit[0],input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=37\n prog.cx(input_qubit[0],input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.y(input_qubit[2]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=22\n prog.cz(input_qubit[0],input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=18\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.cx(input_qubit[3],input_qubit[0]) # number=31\n prog.z(input_qubit[3]) # number=32\n prog.cx(input_qubit[3],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2151.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=74\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=70\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit414.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=66\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.cx(input_qubit[0],input_qubit[2]) # number=63\n prog.x(input_qubit[2]) # number=64\n prog.cx(input_qubit[0],input_qubit[2]) # number=65\n prog.cx(input_qubit[0],input_qubit[2]) # number=56\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy330.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=15\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=12\n prog.cz(input_qubit[1],input_qubit[2]) # number=13\n prog.h(input_qubit[2]) # number=14\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.h(input_qubit[1]) # number=11\n prog.swap(input_qubit[2],input_qubit[0]) # number=8\n prog.swap(input_qubit[2],input_qubit[0]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit621.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=6\n prog.cz(input_qubit[2],input_qubit[1]) # number=7\n prog.h(input_qubit[1]) # number=8\n prog.z(input_qubit[2]) # number=3\n prog.y(input_qubit[2]) # number=5\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class54.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=14\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[1],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=11\n prog.cz(input_qubit[3],input_qubit[2]) # number=12\n prog.h(input_qubit[2]) # number=13\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy481.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[2]) # number=8\n prog.x(input_qubit[2]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit61.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[1]) # number=29\n prog.cz(input_qubit[3],input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=31\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=48\n prog.x(input_qubit[0]) # number=49\n prog.cx(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[1],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.h(input_qubit[4]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.x(input_qubit[1]) # number=10\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=57\n prog.cz(input_qubit[0],input_qubit[2]) # number=58\n prog.h(input_qubit[2]) # number=59\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=42\n prog.cz(input_qubit[0],input_qubit[3]) # number=43\n prog.h(input_qubit[3]) # number=44\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1326.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=10\n prog.h(input_qubit[3]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2199.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[3],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.z(input_qubit[3]) # number=27\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[2]) # number=36\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2545.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[1],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit267.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy47.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=51\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[1],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[1]) # number=46\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1042.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=5\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=2\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=4\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class16.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=31\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.x(input_qubit[3]) # number=15\n prog.rx(1.8001325905069514,input_qubit[3]) # number=18\n prog.z(input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[1]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.cx(input_qubit[0],input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[1]) # number=21\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.x(input_qubit[1]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.y(input_qubit[0]) # number=12\n prog.y(input_qubit[0]) # number=13\n prog.z(input_qubit[2]) # number=26\n prog.cx(input_qubit[2],input_qubit[1]) # number=23\n prog.x(input_qubit[0]) # number=19\n prog.x(input_qubit[0]) # number=20\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2855.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.rx(2.9845130209103035,input_qubit[2]) # number=7\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.rx(1.6807520696705391,input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit708.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=51\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.x(input_qubit[1]) # number=41\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1197.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=32\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.cx(input_qubit[2],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class189.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=16\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=5\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=13\n c.append(cirq.X.on(input_qubit[1])) # number=14\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=15\n c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=6\n c.append(cirq.rx(-1.0053096491487337).on(input_qubit[2])) # number=10\n c.append(cirq.X.on(input_qubit[3])) # number=8\n c.append(cirq.X.on(input_qubit[3])) # number=9\n c.append(cirq.X.on(input_qubit[2])) # number=11\n c.append(cirq.X.on(input_qubit[2])) # number=12\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class451.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n prog.swap(input_qubit[3],input_qubit[0]) # number=8\n prog.swap(input_qubit[3],input_qubit[0]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_Class129.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.y(input_qubit[2]) # number=9\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[2]) # number=12\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.y(input_qubit[2]) # number=7\n prog.y(input_qubit[2]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_Class287.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=28\n prog.cz(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=30\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.rx(2.708052867394402,input_qubit[1]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[2]) # number=16\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[3]) # number=25\n prog.z(input_qubit[1]) # number=20\n prog.z(input_qubit[3]) # number=31\n prog.h(input_qubit[0]) # number=22\n prog.cz(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=24\n prog.z(input_qubit[2]) # number=15\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.y(input_qubit[2]) # number=18\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2654.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=16\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class77.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=32\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.rx(-3.1101767270538954,input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=26\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.z(input_qubit[3]) # number=24\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[3]) # number=28\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2039.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=38\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=28\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n prog.x(input_qubit[0]) # number=36\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=34\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.z(input_qubit[1]) # number=31\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC560.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=56\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=32\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.h(input_qubit[1]) # number=50\n prog.cz(input_qubit[0],input_qubit[1]) # number=51\n prog.h(input_qubit[1]) # number=52\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=42\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[4]) # number=46\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=53\n prog.cz(input_qubit[0],input_qubit[2]) # number=54\n prog.h(input_qubit[2]) # number=55\n prog.x(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=47\n prog.cz(input_qubit[0],input_qubit[2]) # number=48\n prog.h(input_qubit[2]) # number=49\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1599.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=4\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=2\n prog.swap(input_qubit[1],input_qubit[0]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class8.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC242.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=54\n prog.z(input_qubit[1]) # number=55\n prog.cx(input_qubit[1],input_qubit[0]) # number=56\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[1],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.x(input_qubit[3]) # number=46\n prog.y(input_qubit[1]) # number=47\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1613.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=4\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC9.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=23\n prog.rx(-0.6848671984825748,input_qubit[1]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=31\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[3],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.z(input_qubit[3]) # number=21\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[3],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2275.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=13\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[0]) # number=8\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.x(input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy182.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=38\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.h(input_qubit[2]) # number=35\n prog.cz(input_qubit[0],input_qubit[2]) # number=36\n prog.h(input_qubit[2]) # number=37\n prog.x(input_qubit[2]) # number=32\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class205.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=57\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.x(input_qubit[4]) # number=53\n prog.cx(input_qubit[2],input_qubit[0]) # number=45\n prog.z(input_qubit[2]) # number=46\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[2],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.h(input_qubit[1]) # number=4\n prog.rx(2.664070570244145,input_qubit[1]) # number=39\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[2]) # number=49\n prog.cz(input_qubit[3],input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=51\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[3]) # number=40\n prog.y(input_qubit[4]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.cx(input_qubit[2],input_qubit[3]) # number=44\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n prog.z(input_qubit[1]) # number=52\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1635.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[0]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC247.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.z(input_qubit[1]) # number=24\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.8902652413026093,input_qubit[2]) # number=13\n\n prog.y(input_qubit[1]) # number=11\n prog.y(input_qubit[1]) # number=12\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2136.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.rx(-0.1602212253330796,input_qubit[1]) # number=36\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=28\n prog.h(input_qubit[4]) # number=31\n prog.x(input_qubit[1]) # number=29\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.x(input_qubit[2]) # number=26\n prog.cx(input_qubit[0],input_qubit[2]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.z(input_qubit[1]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC837.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=67\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.x(input_qubit[2]) # number=55\n prog.cx(input_qubit[0],input_qubit[2]) # number=56\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit346.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=33\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.y(input_qubit[2]) # number=18\n prog.z(input_qubit[3]) # number=28\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[1]) # number=19\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[2],input_qubit[0]) # number=16\n prog.h(input_qubit[0]) # number=17\n prog.y(input_qubit[1]) # number=26\n prog.y(input_qubit[1]) # number=27\n prog.swap(input_qubit[1],input_qubit[0]) # number=29\n prog.swap(input_qubit[1],input_qubit[0]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.x(input_qubit[1]) # number=32\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2102.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[1],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.cx(input_qubit[1],input_qubit[0]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit271.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=47\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.rx(-0.9927432785343745,input_qubit[1]) # number=43\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.h(input_qubit[0]) # number=44\n prog.cz(input_qubit[2],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=46\n prog.z(input_qubit[2]) # number=38\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cz(input_qubit[2],input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit3211.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=42\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=39\n prog.x(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=34\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=35\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.z(input_qubit[1]) # number=31\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit860.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=21\n prog.cz(input_qubit[0],input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=27\n prog.cz(input_qubit[0],input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=36\n prog.x(input_qubit[3]) # number=37\n prog.cx(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.y(input_qubit[3]) # number=20\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=19\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1964.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=41\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[4]) # number=27\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[4]) # number=34\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=38\n prog.x(input_qubit[2]) # number=39\n prog.cx(input_qubit[0],input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.y(input_qubit[1]) # number=26\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[2]) # number=31\n prog.cz(input_qubit[4],input_qubit[2]) # number=32\n prog.h(input_qubit[2]) # number=33\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy929.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.swap(input_qubit[2],input_qubit[0]) # number=8\n prog.swap(input_qubit[2],input_qubit[0]) # number=9\n prog.x(input_qubit[3]) # number=10\n prog.x(input_qubit[3]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC167.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=13\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[1],input_qubit[0]) # number=16\n prog.h(input_qubit[1]) # number=20\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[3],input_qubit[0]) # number=24\n prog.z(input_qubit[3]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=21\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[2],input_qubit[0]) # number=22\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2573.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.y(input_qubit[3]) # number=8\n prog.y(input_qubit[3]) # number=9\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC329.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=47\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.cx(input_qubit[3],input_qubit[0]) # number=32\n prog.z(input_qubit[3]) # number=33\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.11938052083641225,input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(1.4765485471872026,input_qubit[2]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=44\n prog.cz(input_qubit[1],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=46\n prog.x(input_qubit[4]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(0.45238934211692994,input_qubit[3]) # number=38\n prog.y(input_qubit[1]) # number=39\n prog.rx(-2.5258404934861938,input_qubit[1]) # number=25\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=24\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(-0.0722566310325653,input_qubit[4]) # number=37\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[2]) # number=26\n prog.x(input_qubit[2]) # number=27\n prog.h(input_qubit[4]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1471.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=56\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=53\n prog.cz(input_qubit[1],input_qubit[0]) # number=54\n prog.h(input_qubit[0]) # number=55\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.h(input_qubit[1]) # number=50\n prog.cz(input_qubit[0],input_qubit[1]) # number=51\n prog.h(input_qubit[1]) # number=52\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=42\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[4]) # number=46\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[0],input_qubit[2]) # number=43\n prog.x(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=47\n prog.cz(input_qubit[0],input_qubit[2]) # number=48\n prog.h(input_qubit[2]) # number=49\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1595.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=74\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.cx(input_qubit[2],input_qubit[1]) # number=70\n prog.cx(input_qubit[1],input_qubit[0]) # number=71\n prog.z(input_qubit[1]) # number=72\n prog.cx(input_qubit[1],input_qubit[0]) # number=73\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit372.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=74\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.cx(input_qubit[0],input_qubit[2]) # number=54\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.cx(input_qubit[0],input_qubit[1]) # number=71\n prog.x(input_qubit[1]) # number=72\n prog.cx(input_qubit[0],input_qubit[1]) # number=73\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.cx(input_qubit[2],input_qubit[1]) # number=70\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit373.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=29\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC153.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=45\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=42\n prog.x(input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=44\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.cx(input_qubit[0],input_qubit[1]) # number=26\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.x(input_qubit[2]) # number=29\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1018.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=10\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.rx(2.0860175219836226,input_qubit[1]) # number=7\n prog.x(input_qubit[0]) # number=5\n prog.x(input_qubit[0]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC163.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=10\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=21\n prog.h(input_qubit[2]) # number=36\n prog.cz(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=38\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[3],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n prog.y(input_qubit[2]) # number=29\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2186.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=41\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.cx(input_qubit[0],input_qubit[2]) # number=35\n prog.cx(input_qubit[0],input_qubit[2]) # number=38\n prog.x(input_qubit[2]) # number=39\n prog.cx(input_qubit[0],input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy219.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=38\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=32\n prog.cz(input_qubit[0],input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=34\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.cx(input_qubit[2],input_qubit[3]) # number=22\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=24\n prog.cz(input_qubit[3],input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[0],input_qubit[2]) # number=29\n prog.x(input_qubit[2]) # number=30\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=21\n prog.x(input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2519.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=33\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.x(input_qubit[2]) # number=12\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.cx(input_qubit[2],input_qubit[0]) # number=30\n prog.z(input_qubit[2]) # number=31\n prog.cx(input_qubit[2],input_qubit[0]) # number=32\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC174.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=45\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.cx(input_qubit[0],input_qubit[2]) # number=42\n prog.x(input_qubit[2]) # number=43\n prog.cx(input_qubit[0],input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=39\n prog.cz(input_qubit[0],input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=41\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[2]) # number=36\n prog.cz(input_qubit[3],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=38\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=19\n prog.cz(input_qubit[2],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=21\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[2],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2885.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=44\n prog.cz(input_qubit[3],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=48\n prog.z(input_qubit[3]) # number=49\n prog.cx(input_qubit[3],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[3],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.rx(0.11938052083641225,input_qubit[1]) # number=36\n prog.cx(input_qubit[1],input_qubit[2]) # number=47\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(1.4765485471872026,input_qubit[2]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.x(input_qubit[4]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(0.45238934211692994,input_qubit[3]) # number=38\n prog.y(input_qubit[1]) # number=39\n prog.rx(-2.5258404934861938,input_qubit[1]) # number=25\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=24\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(-0.0722566310325653,input_qubit[4]) # number=37\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[2]) # number=26\n prog.x(input_qubit[2]) # number=27\n prog.h(input_qubit[4]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1821.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=35\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=26\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.y(input_qubit[3]) # number=25\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=32\n prog.x(input_qubit[0]) # number=33\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[0],input_qubit[1]) # number=28\n prog.x(input_qubit[1]) # number=29\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.y(input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[1],input_qubit[2]) # number=31\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy669.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=38\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[1]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.swap(input_qubit[3],input_qubit[0]) # number=22\n prog.swap(input_qubit[3],input_qubit[0]) # number=23\n prog.swap(input_qubit[1],input_qubit[0]) # number=27\n prog.swap(input_qubit[1],input_qubit[0]) # number=28\n prog.swap(input_qubit[3],input_qubit[0]) # number=34\n prog.swap(input_qubit[3],input_qubit[0]) # number=35\n prog.x(input_qubit[0]) # number=36\n prog.x(input_qubit[0]) # number=37\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2585.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=37\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=32\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.cx(input_qubit[2],input_qubit[0]) # number=34\n prog.z(input_qubit[2]) # number=35\n prog.cx(input_qubit[2],input_qubit[0]) # number=36\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC199.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[3]) # number=7\n prog.y(input_qubit[3]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_QC73.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=13\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.rx(2.0860175219836226,input_qubit[1]) # number=7\n prog.x(input_qubit[0]) # number=5\n prog.x(input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy214.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=8\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.rx(2.7457519792374794,input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy16.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=51\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.cx(input_qubit[0],input_qubit[1]) # number=48\n prog.x(input_qubit[1]) # number=49\n prog.cx(input_qubit[0],input_qubit[1]) # number=50\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1199.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC49.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=22\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class120.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=14\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[2]) # number=8\n prog.y(input_qubit[2]) # number=9\n prog.y(input_qubit[3]) # number=10\n prog.y(input_qubit[3]) # number=11\n prog.x(input_qubit[1]) # number=12\n prog.x(input_qubit[1]) # number=13\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit823.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=25\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=22\n prog.cz(input_qubit[0],input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=24\n prog.x(input_qubit[2]) # number=12\n prog.cx(input_qubit[0],input_qubit[2]) # number=13\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.cx(input_qubit[2],input_qubit[1]) # number=10\n prog.z(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit145.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=31\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.x(input_qubit[2]) # number=12\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.cx(input_qubit[2],input_qubit[0]) # number=28\n prog.z(input_qubit[2]) # number=29\n prog.cx(input_qubit[2],input_qubit[0]) # number=30\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy161.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=15\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.y(input_qubit[3]) # number=8\n prog.y(input_qubit[3]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=12\n prog.x(input_qubit[2]) # number=13\n prog.cx(input_qubit[0],input_qubit[2]) # number=14\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC537.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=7\n prog.x(input_qubit[2]) # number=8\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.cx(input_qubit[3],input_qubit[1]) # number=10\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[0]) # number=11\n prog.x(input_qubit[0]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_Class304.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[1]) # number=29\n prog.cz(input_qubit[3],input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=31\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=48\n prog.x(input_qubit[0]) # number=49\n prog.cx(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[1],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.h(input_qubit[4]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.x(input_qubit[1]) # number=10\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=57\n prog.cz(input_qubit[0],input_qubit[2]) # number=58\n prog.h(input_qubit[2]) # number=59\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=42\n prog.cz(input_qubit[0],input_qubit[3]) # number=43\n prog.h(input_qubit[3]) # number=44\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1326.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=51\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=48\n prog.z(input_qubit[1]) # number=49\n prog.cx(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.x(input_qubit[3]) # number=46\n prog.y(input_qubit[1]) # number=47\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1265.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[0],input_qubit[2]) # number=7\n prog.x(input_qubit[2]) # number=8\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.cx(input_qubit[0],input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[2]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC96.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[0]) # number=8\n prog.x(input_qubit[0]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_QC110.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[1]) # number=8\n prog.x(input_qubit[1]) # number=9\n prog.x(input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit577.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=31\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.x(input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.rx(2.708052867394402,input_qubit[1]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[2]) # number=16\n prog.h(input_qubit[0]) # number=28\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[3]) # number=25\n prog.z(input_qubit[1]) # number=20\n prog.h(input_qubit[0]) # number=22\n prog.cz(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=24\n prog.z(input_qubit[2]) # number=15\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.y(input_qubit[2]) # number=18\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2128.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=6\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.x(input_qubit[1]) # number=2\n prog.x(input_qubit[1]) # number=3\n prog.swap(input_qubit[1],input_qubit[0]) # number=4\n prog.swap(input_qubit[1],input_qubit[0]) # number=5\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class17.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.48380526865282825,input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.y(input_qubit[3]) # number=18\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=28\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[0],input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=36\n prog.x(input_qubit[1]) # number=32\n prog.cx(input_qubit[0],input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=22\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2506.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=44\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.y(input_qubit[2]) # number=36\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=14\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.cx(input_qubit[3],input_qubit[1]) # number=35\n prog.y(input_qubit[2]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=22\n prog.cz(input_qubit[0],input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=18\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.cx(input_qubit[3],input_qubit[0]) # number=31\n prog.cx(input_qubit[3],input_qubit[0]) # number=37\n prog.z(input_qubit[3]) # number=38\n prog.cx(input_qubit[3],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[3],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy3190.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.cx(input_qubit[2],input_qubit[0]) # number=37\n prog.z(input_qubit[2]) # number=38\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cz(input_qubit[2],input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2954.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.cx(input_qubit[2],input_qubit[0]) # number=37\n prog.z(input_qubit[2]) # number=38\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.cx(input_qubit[2],input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2429.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=28\n prog.cx(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.cx(input_qubit[3],input_qubit[2]) # number=22\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=19\n prog.cz(input_qubit[2],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=21\n prog.cx(input_qubit[2],input_qubit[3]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2105.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=62\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[1],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.z(input_qubit[1]) # number=37\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=56\n prog.cz(input_qubit[3],input_qubit[0]) # number=57\n prog.h(input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=47\n prog.x(input_qubit[4]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=44\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[3]) # number=59\n prog.cz(input_qubit[4],input_qubit[3]) # number=60\n prog.h(input_qubit[3]) # number=61\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.y(input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[4],input_qubit[3]) # number=55\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1863.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=51\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.z(input_qubit[1]) # number=30\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.x(input_qubit[3]) # number=46\n prog.y(input_qubit[1]) # number=47\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1261.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=42\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=33\n prog.h(input_qubit[1]) # number=39\n prog.cz(input_qubit[0],input_qubit[1]) # number=40\n prog.h(input_qubit[1]) # number=41\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=35\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.z(input_qubit[1]) # number=31\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit859.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=39\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.cx(input_qubit[1],input_qubit[0]) # number=31\n prog.h(input_qubit[2]) # number=34\n prog.x(input_qubit[0]) # number=32\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[2],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=23\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[4],input_qubit[1]) # number=35\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.cx(input_qubit[1],input_qubit[3]) # number=27\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit904.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=8\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.cx(input_qubit[0],input_qubit[1]) # number=5\n prog.x(input_qubit[1]) # number=6\n prog.cx(input_qubit[0],input_qubit[1]) # number=7\n prog.x(input_qubit[1]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy39.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=48\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.x(input_qubit[2]) # number=36\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.cx(input_qubit[0],input_qubit[2]) # number=45\n prog.x(input_qubit[2]) # number=46\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy246.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=43\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=40\n prog.cz(input_qubit[0],input_qubit[3]) # number=41\n prog.h(input_qubit[3]) # number=42\n prog.h(input_qubit[3]) # number=36\n prog.cz(input_qubit[0],input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=38\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[1]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=39\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.swap(input_qubit[3],input_qubit[0]) # number=22\n prog.swap(input_qubit[3],input_qubit[0]) # number=23\n prog.swap(input_qubit[1],input_qubit[0]) # number=27\n prog.swap(input_qubit[1],input_qubit[0]) # number=28\n prog.swap(input_qubit[3],input_qubit[0]) # number=34\n prog.swap(input_qubit[3],input_qubit[0]) # number=35\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3104.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=18\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[2])) # number=15\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=14\n c.append(cirq.X.on(input_qubit[1])) # number=10\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=11\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=12\n c.append(cirq.H.on(input_qubit[0])) # number=13\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.X.on(input_qubit[1])) # number=16\n c.append(cirq.X.on(input_qubit[1])) # number=17\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =4000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class672.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.y(input_qubit[1]) # number=5\n prog.y(input_qubit[1]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy26.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=73\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=70\n prog.cz(input_qubit[0],input_qubit[2]) # number=71\n prog.h(input_qubit[2]) # number=72\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class366.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.rx(-3.1101767270538954,input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=26\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[3]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=32\n prog.z(input_qubit[3]) # number=33\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[3]) # number=28\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2559.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=41\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.rx(-3.1101767270538954,input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=26\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[3]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[3],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=38\n prog.z(input_qubit[3]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n prog.z(input_qubit[3]) # number=36\n prog.cx(input_qubit[3],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit3076.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[0]) # number=5\n prog.x(input_qubit[0]) # number=6\n prog.y(input_qubit[2]) # number=7\n prog.y(input_qubit[2]) # number=8\n prog.swap(input_qubit[1],input_qubit[0]) # number=9\n prog.swap(input_qubit[1],input_qubit[0]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit176.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=64\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.h(input_qubit[0]) # number=61\n prog.cz(input_qubit[1],input_qubit[0]) # number=62\n prog.h(input_qubit[0]) # number=63\n prog.z(input_qubit[1]) # number=53\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[1],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[4]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.rx(-0.22619467105846497,input_qubit[3]) # number=60\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.h(input_qubit[1]) # number=56\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(-2.9845130209103035,input_qubit[4]) # number=55\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1851.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=49\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[1]) # number=26\n prog.cz(input_qubit[4],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=28\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[4],input_qubit[1]) # number=35\n prog.rx(0.8011061266653969,input_qubit[2]) # number=37\n prog.h(input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.h(input_qubit[1]) # number=46\n prog.cz(input_qubit[0],input_qubit[1]) # number=47\n prog.h(input_qubit[1]) # number=48\n prog.x(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=44\n prog.x(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=45\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=41\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[0]) # number=23\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[2]) # number=15\n prog.h(input_qubit[4]) # number=29\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1220.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.cx(input_qubit[2],input_qubit[0]) # number=45\n prog.z(input_qubit[2]) # number=46\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[2],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.h(input_qubit[1]) # number=4\n prog.rx(2.664070570244145,input_qubit[1]) # number=39\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.cx(input_qubit[3],input_qubit[2]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[3]) # number=40\n prog.y(input_qubit[4]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.cx(input_qubit[2],input_qubit[3]) # number=44\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1297.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=63\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[3]) # number=59\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[4],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=56\n prog.cz(input_qubit[4],input_qubit[0]) # number=57\n prog.h(input_qubit[0]) # number=58\n prog.cx(input_qubit[4],input_qubit[0]) # number=60\n prog.z(input_qubit[4]) # number=61\n prog.cx(input_qubit[4],input_qubit[0]) # number=62\n prog.cx(input_qubit[4],input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[4],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(-1.0430087609918113,input_qubit[4]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=52\n prog.x(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=54\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.x(input_qubit[1]) # number=10\n prog.rx(-0.06597344572538572,input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.h(input_qubit[4]) # number=35\n\n\n prog.h(input_qubit[0]) # number=17\n prog.rx(2.4912829742967055,input_qubit[2]) # number=26\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1922.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=49\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[4],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.z(input_qubit[4]) # number=33\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[4],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(-1.0430087609918113,input_qubit[4]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.x(input_qubit[0]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=42\n prog.x(input_qubit[1]) # number=10\n prog.rx(-0.06597344572538572,input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.h(input_qubit[4]) # number=35\n\n\n prog.h(input_qubit[0]) # number=17\n prog.rx(2.4912829742967055,input_qubit[2]) # number=26\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1229.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[4],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[4],input_qubit[0]) # number=46\n prog.z(input_qubit[4]) # number=47\n prog.cx(input_qubit[4],input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[4],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(-1.0430087609918113,input_qubit[4]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.x(input_qubit[0]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=42\n prog.x(input_qubit[1]) # number=10\n prog.rx(-0.06597344572538572,input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.h(input_qubit[4]) # number=35\n\n\n prog.h(input_qubit[0]) # number=17\n prog.rx(2.4912829742967055,input_qubit[2]) # number=26\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1349.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=11\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=35\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.h(input_qubit[1]) # number=36\n prog.cz(input_qubit[2],input_qubit[1]) # number=37\n prog.h(input_qubit[1]) # number=38\n prog.x(input_qubit[1]) # number=23\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2980.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=38\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.cx(input_qubit[2],input_qubit[1]) # number=34\n prog.x(input_qubit[1]) # number=23\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2726.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=38\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.x(input_qubit[3]) # number=14\n prog.h(input_qubit[3]) # number=32\n prog.cz(input_qubit[0],input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=34\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.cx(input_qubit[2],input_qubit[3]) # number=22\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=24\n prog.cz(input_qubit[3],input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[0],input_qubit[2]) # number=29\n prog.x(input_qubit[2]) # number=30\n prog.h(input_qubit[2]) # number=35\n prog.cz(input_qubit[0],input_qubit[2]) # number=36\n prog.h(input_qubit[2]) # number=37\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=21\n prog.x(input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2518.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=41\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[4]) # number=27\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[4]) # number=34\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.y(input_qubit[1]) # number=26\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[2]) # number=31\n prog.cz(input_qubit[4],input_qubit[2]) # number=32\n prog.h(input_qubit[2]) # number=33\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit931.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=7\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[2]) # number=2\n prog.cx(input_qubit[2],input_qubit[0]) # number=4\n prog.z(input_qubit[2]) # number=5\n prog.cx(input_qubit[2],input_qubit[0]) # number=6\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC29.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[1]) # number=31\n prog.cz(input_qubit[2],input_qubit[1]) # number=32\n prog.h(input_qubit[1]) # number=33\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=24\n prog.cz(input_qubit[3],input_qubit[0]) # number=25\n prog.h(input_qubit[0]) # number=26\n prog.cx(input_qubit[3],input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=36\n prog.z(input_qubit[3]) # number=37\n prog.cx(input_qubit[3],input_qubit[0]) # number=38\n prog.cx(input_qubit[3],input_qubit[0]) # number=30\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2530.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=5\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class20.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=28\n prog.cx(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=13\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[1],input_qubit[0]) # number=16\n prog.h(input_qubit[1]) # number=20\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[3],input_qubit[0]) # number=24\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=21\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[2],input_qubit[0]) # number=22\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2579.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=41\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=19\n prog.cz(input_qubit[0],input_qubit[3]) # number=20\n prog.h(input_qubit[3]) # number=21\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.48380526865282825,input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.y(input_qubit[3]) # number=18\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[0],input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=36\n prog.h(input_qubit[1]) # number=38\n prog.cz(input_qubit[0],input_qubit[1]) # number=39\n prog.h(input_qubit[1]) # number=40\n prog.x(input_qubit[1]) # number=32\n prog.cx(input_qubit[0],input_qubit[1]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=37\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=22\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit3024.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=11\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=6\n prog.cz(input_qubit[0],input_qubit[1]) # number=7\n prog.h(input_qubit[1]) # number=8\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.y(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.swap(input_qubit[1],input_qubit[0]) # number=9\n prog.swap(input_qubit[1],input_qubit[0]) # number=10\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class157.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=13\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=5\n c.append(cirq.X.on(input_qubit[1])) # number=7\n c.append(cirq.SWAP.on(input_qubit[2],input_qubit[0])) # number=6\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=10\n c.append(cirq.X.on(input_qubit[3])) # number=11\n c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=12\n c.append(cirq.X.on(input_qubit[3])) # number=9\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class185.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC52.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.z(input_qubit[3]) # number=7\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[1]) # number=8\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[3],input_qubit[0]) # number=5\n prog.swap(input_qubit[3],input_qubit[0]) # number=6\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy89.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=28\n prog.cz(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=30\n prog.z(input_qubit[3]) # number=10\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.rx(2.708052867394402,input_qubit[1]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.y(input_qubit[2]) # number=16\n prog.cx(input_qubit[1],input_qubit[0]) # number=19\n prog.h(input_qubit[3]) # number=25\n prog.z(input_qubit[1]) # number=20\n prog.z(input_qubit[3]) # number=31\n prog.h(input_qubit[0]) # number=22\n prog.cz(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=24\n prog.z(input_qubit[2]) # number=15\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.y(input_qubit[2]) # number=18\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2645.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=22\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.Y.on(input_qubit[2])) # number=13\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=10\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=11\n c.append(cirq.H.on(input_qubit[0])) # number=12\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.H.on(input_qubit[1])) # number=16\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.Y.on(input_qubit[1])) # number=14\n c.append(cirq.Y.on(input_qubit[1])) # number=15\n c.append(cirq.H.on(input_qubit[0])) # number=19\n c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) # number=20\n c.append(cirq.H.on(input_qubit[0])) # number=21\n c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=18\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =4000\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class974.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=28\n prog.cx(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.cx(input_qubit[3],input_qubit[2]) # number=22\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=19\n prog.cz(input_qubit[2],input_qubit[0]) # number=20\n prog.h(input_qubit[0]) # number=21\n prog.cx(input_qubit[2],input_qubit[3]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2110.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=8\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[3]) # number=7\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.y(input_qubit[1]) # number=5\n prog.y(input_qubit[1]) # number=6\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy23.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=10\n prog.h(input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=11\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[1]) # number=32\n prog.cx(input_qubit[0],input_qubit[1]) # number=33\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2203.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=4\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=2\n prog.cx(input_qubit[1],input_qubit[0]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class7.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.x(input_qubit[3]) # number=1\n prog.h(input_qubit[0]) # number=18\n prog.x(input_qubit[1]) # number=28\n prog.cz(input_qubit[3],input_qubit[0]) # number=19\n prog.h(input_qubit[2]) # number=24\n prog.h(input_qubit[0]) # number=20\n prog.rx(-1.8378317023500288,input_qubit[1]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=32\n prog.z(input_qubit[3]) # number=33\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[3]) # number=16\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[3]) # number=29\n prog.cz(input_qubit[0],input_qubit[3]) # number=30\n prog.h(input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.z(input_qubit[1]) # number=26\n\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[2]) # number=12\n prog.z(input_qubit[1]) # number=27\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2682.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[0],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[3],input_qubit[0]) # number=37\n prog.z(input_qubit[3]) # number=38\n prog.cx(input_qubit[3],input_qubit[0]) # number=39\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=14\n prog.h(input_qubit[1]) # number=30\n prog.cz(input_qubit[2],input_qubit[0]) # number=15\n prog.h(input_qubit[0]) # number=16\n prog.cx(input_qubit[0],input_qubit[2]) # number=20\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=17\n prog.cx(input_qubit[0],input_qubit[2]) # number=23\n prog.x(input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.cx(input_qubit[0],input_qubit[2]) # number=19\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2378.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=45\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[1],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=39\n prog.cz(input_qubit[1],input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[1],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.x(input_qubit[2]) # number=26\n prog.cx(input_qubit[0],input_qubit[2]) # number=27\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[2],input_qubit[4]) # number=37\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit947.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=4\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class5.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=44\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.cx(input_qubit[0],input_qubit[2]) # number=35\n prog.x(input_qubit[2]) # number=36\n prog.h(input_qubit[2]) # number=41\n prog.cz(input_qubit[0],input_qubit[2]) # number=42\n prog.h(input_qubit[2]) # number=43\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy231.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.y(input_qubit[2]) # number=5\n prog.y(input_qubit[2]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC48.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=31\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.x(input_qubit[3]) # number=1\n prog.h(input_qubit[0]) # number=18\n prog.cz(input_qubit[3],input_qubit[0]) # number=19\n prog.h(input_qubit[2]) # number=24\n prog.h(input_qubit[0]) # number=20\n prog.rx(-1.8378317023500288,input_qubit[1]) # number=25\n prog.z(input_qubit[3]) # number=14\n prog.cx(input_qubit[3],input_qubit[0]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[3]) # number=16\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[3]) # number=28\n prog.cz(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=23\n prog.z(input_qubit[1]) # number=26\n\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[2]) # number=12\n prog.z(input_qubit[1]) # number=27\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2161.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=57\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.x(input_qubit[4]) # number=53\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[2],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.z(input_qubit[2]) # number=46\n prog.cx(input_qubit[2],input_qubit[0]) # number=47\n prog.h(input_qubit[1]) # number=4\n prog.rx(2.664070570244145,input_qubit[1]) # number=39\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[2]) # number=49\n prog.cz(input_qubit[3],input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=51\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[3]) # number=40\n prog.y(input_qubit[4]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.cx(input_qubit[2],input_qubit[3]) # number=44\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n prog.z(input_qubit[1]) # number=52\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1638.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=11\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.rx(2.9845130209103035,input_qubit[2]) # number=7\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.rx(1.6807520696705391,input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=9\n prog.swap(input_qubit[1],input_qubit[0]) # number=10\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit450.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.x(input_qubit[2]) # number=34\n prog.y(input_qubit[1]) # number=19\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.y(input_qubit[3]) # number=20\n prog.y(input_qubit[1]) # number=12\n prog.rx(-2.158274153016188,input_qubit[3]) # number=24\n prog.h(input_qubit[0]) # number=16\n prog.cz(input_qubit[2],input_qubit[0]) # number=17\n prog.h(input_qubit[0]) # number=18\n prog.cx(input_qubit[1],input_qubit[0]) # number=21\n prog.z(input_qubit[1]) # number=22\n prog.cx(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[2],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.x(input_qubit[0]) # number=35\n prog.x(input_qubit[0]) # number=36\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2749.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=32\n prog.cz(input_qubit[0],input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=29\n prog.cz(input_qubit[0],input_qubit[2]) # number=30\n prog.h(input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.y(input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.z(input_qubit[1]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[3],input_qubit[0]) # number=13\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2440.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[1]) # number=31\n prog.cz(input_qubit[2],input_qubit[1]) # number=32\n prog.h(input_qubit[1]) # number=33\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=24\n prog.cz(input_qubit[3],input_qubit[0]) # number=25\n prog.h(input_qubit[0]) # number=26\n prog.cx(input_qubit[3],input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=36\n prog.z(input_qubit[3]) # number=37\n prog.cx(input_qubit[3],input_qubit[0]) # number=38\n prog.cx(input_qubit[3],input_qubit[0]) # number=30\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2529.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.y(input_qubit[3]) # number=8\n prog.y(input_qubit[3]) # number=9\n prog.rx(0.5466371217246238,input_qubit[1]) # number=10\n prog.cx(input_qubit[1],input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy541.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=32\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.cx(input_qubit[0],input_qubit[1]) # number=26\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=42\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[4]) # number=46\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[0],input_qubit[2]) # number=43\n prog.x(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=47\n prog.cz(input_qubit[0],input_qubit[2]) # number=48\n prog.h(input_qubit[2]) # number=49\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1363.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=56\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[4],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[4],input_qubit[0]) # number=46\n prog.z(input_qubit[4]) # number=47\n prog.cx(input_qubit[4],input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[4],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(-1.0430087609918113,input_qubit[4]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=52\n prog.x(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=54\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.x(input_qubit[1]) # number=10\n prog.rx(-0.06597344572538572,input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.h(input_qubit[4]) # number=35\n\n\n prog.h(input_qubit[0]) # number=17\n prog.rx(2.4912829742967055,input_qubit[2]) # number=26\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1572.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=67\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC363.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=9\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=6\n prog.cz(input_qubit[0],input_qubit[1]) # number=7\n prog.h(input_qubit[1]) # number=8\n prog.cx(input_qubit[0],input_qubit[1]) # number=5\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[0]) # number=3\n prog.x(input_qubit[0]) # number=4\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC106.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=57\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[1]) # number=29\n prog.cz(input_qubit[3],input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=31\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[1],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.x(input_qubit[0]) # number=49\n prog.cx(input_qubit[1],input_qubit[0]) # number=50\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[4]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.x(input_qubit[1]) # number=10\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.x(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=42\n prog.cz(input_qubit[0],input_qubit[3]) # number=43\n prog.h(input_qubit[3]) # number=44\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1209.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=18\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.rx(2.0860175219836226,input_qubit[1]) # number=7\n prog.x(input_qubit[0]) # number=5\n prog.x(input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n prog.x(input_qubit[1]) # number=16\n prog.x(input_qubit[1]) # number=17\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class336.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=54\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.x(input_qubit[2]) # number=46\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC271.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=21\n prog.cz(input_qubit[0],input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=27\n prog.cz(input_qubit[0],input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.x(input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.rx(-0.364424747816416,input_qubit[3]) # number=36\n prog.y(input_qubit[3]) # number=20\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=19\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2219.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=8\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=5\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.x(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC118.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=20\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=12\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=13\n c.append(cirq.H.on(input_qubit[0])) # number=14\n c.append(cirq.H.on(input_qubit[0])) # number=15\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=16\n c.append(cirq.H.on(input_qubit[0])) # number=17\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=18\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=19\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2820\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class518.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=5\n# total number=45\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[1],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=39\n prog.cz(input_qubit[1],input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[1],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.x(input_qubit[2]) # number=26\n prog.cx(input_qubit[0],input_qubit[2]) # number=27\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[2],input_qubit[4]) # number=37\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class947.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[1],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.z(input_qubit[1]) # number=37\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[3],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=47\n prog.x(input_qubit[4]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=44\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.y(input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class1396.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=13\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=10\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=11\n c.append(cirq.H.on(input_qubit[0])) # number=12\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=8\n c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=9\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =0\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class132.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=4\n# total number=39\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.x(input_qubit[2]) # number=34\n prog.y(input_qubit[1]) # number=19\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.y(input_qubit[3]) # number=20\n prog.y(input_qubit[1]) # number=12\n prog.rx(-2.158274153016188,input_qubit[3]) # number=24\n prog.h(input_qubit[0]) # number=16\n prog.cz(input_qubit[2],input_qubit[0]) # number=17\n prog.h(input_qubit[0]) # number=18\n prog.cx(input_qubit[1],input_qubit[0]) # number=21\n prog.z(input_qubit[1]) # number=22\n prog.cx(input_qubit[1],input_qubit[0]) # number=23\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[2],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.x(input_qubit[0]) # number=35\n prog.x(input_qubit[0]) # number=36\n prog.y(input_qubit[3]) # number=37\n prog.y(input_qubit[3]) # number=38\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy3012.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=12\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[1]) # number=8\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=2\n prog.swap(input_qubit[1],input_qubit[0]) # number=3\n prog.x(input_qubit[1]) # number=5\n prog.h(input_qubit[1]) # number=9\n prog.cz(input_qubit[0],input_qubit[1]) # number=10\n prog.h(input_qubit[1]) # number=11\n prog.rx(-2.73004401596953,input_qubit[1]) # number=6\n prog.z(input_qubit[1]) # number=4\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC303.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.cx(input_qubit[2],input_qubit[0]) # number=37\n prog.cx(input_qubit[2],input_qubit[0]) # number=43\n prog.z(input_qubit[2]) # number=44\n prog.cx(input_qubit[2],input_qubit[0]) # number=45\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cz(input_qubit[2],input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2957.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.x(input_qubit[1]) # number=48\n prog.h(input_qubit[1]) # number=26\n prog.cz(input_qubit[4],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=28\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[4],input_qubit[1]) # number=35\n prog.z(input_qubit[4]) # number=46\n prog.rx(0.8011061266653969,input_qubit[2]) # number=37\n prog.h(input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.x(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=44\n prog.x(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=45\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=41\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[4]) # number=47\n prog.x(input_qubit[0]) # number=23\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[2]) # number=15\n prog.h(input_qubit[4]) # number=29\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1565.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=22\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class127.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=9\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy37.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=25\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC133.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC626.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=21\n prog.cz(input_qubit[0],input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=27\n prog.cz(input_qubit[0],input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=29\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.x(input_qubit[3]) # number=41\n prog.cx(input_qubit[0],input_qubit[3]) # number=42\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.rx(-0.364424747816416,input_qubit[3]) # number=36\n prog.y(input_qubit[3]) # number=20\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=19\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2740.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=49\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.h(input_qubit[3]) # number=46\n prog.cz(input_qubit[0],input_qubit[3]) # number=47\n prog.h(input_qubit[3]) # number=48\n prog.x(input_qubit[3]) # number=41\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.33300882128051834,input_qubit[2]) # number=36\n prog.h(input_qubit[0]) # number=35\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.z(input_qubit[3]) # number=24\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy3346.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=54\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=44\n prog.cz(input_qubit[3],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=48\n prog.z(input_qubit[3]) # number=49\n prog.cx(input_qubit[3],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[3],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.rx(0.11938052083641225,input_qubit[1]) # number=36\n prog.cx(input_qubit[1],input_qubit[2]) # number=47\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(1.4765485471872026,input_qubit[2]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.x(input_qubit[4]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(0.45238934211692994,input_qubit[3]) # number=38\n prog.y(input_qubit[1]) # number=39\n prog.rx(-2.5258404934861938,input_qubit[1]) # number=25\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=24\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(-0.0722566310325653,input_qubit[4]) # number=37\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[2]) # number=26\n prog.x(input_qubit[2]) # number=27\n prog.h(input_qubit[4]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1819.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=16\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n prog.cx(input_qubit[1],input_qubit[3]) # number=12\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=7\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_Class492.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=11\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2205.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=15\n prog.cz(input_qubit[0],input_qubit[3]) # number=16\n prog.h(input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[1]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=23\n prog.cz(input_qubit[2],input_qubit[0]) # number=24\n prog.h(input_qubit[0]) # number=25\n prog.y(input_qubit[2]) # number=30\n prog.cx(input_qubit[2],input_qubit[0]) # number=11\n prog.cx(input_qubit[2],input_qubit[0]) # number=18\n prog.h(input_qubit[0]) # number=26\n prog.x(input_qubit[2]) # number=31\n prog.cz(input_qubit[2],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2346.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.y(input_qubit[3]) # number=8\n prog.x(input_qubit[2]) # number=10\n prog.x(input_qubit[2]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC782.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=45\n prog.z(input_qubit[1]) # number=46\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[4]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1163.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.cx(input_qubit[2],input_qubit[0]) # number=37\n prog.z(input_qubit[2]) # number=38\n prog.cx(input_qubit[2],input_qubit[0]) # number=39\n prog.cx(input_qubit[2],input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2424.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.y(input_qubit[2]) # number=18\n prog.z(input_qubit[3]) # number=28\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[2],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[1]) # number=19\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[2],input_qubit[0]) # number=16\n prog.h(input_qubit[0]) # number=17\n prog.y(input_qubit[1]) # number=26\n prog.y(input_qubit[1]) # number=27\n prog.swap(input_qubit[1],input_qubit[0]) # number=29\n prog.swap(input_qubit[1],input_qubit[0]) # number=30\n prog.x(input_qubit[0]) # number=31\n prog.x(input_qubit[0]) # number=32\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2351.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=7\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=2\n prog.swap(input_qubit[1],input_qubit[0]) # number=3\n prog.z(input_qubit[1]) # number=4\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit89.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=24\nimport pyquil\nfrom pyquil.api import QVMConnection\nfrom pyquil import Program, get_qc,list_quantum_computers\nfrom pyquil.gates import *\nimport numpy as np\nfrom math import floor,sqrt,pi\nfrom functools import reduce\n\nconn = QVMConnection()\n\ndef matrix_controlled_z(n: int, y: str) -> np.ndarray:\n # implement Z_f\n # or controlled Z gate with X flip (placing CZ is arbitrary)\n I = np.identity(2 ** n)\n v = int(y, 2)\n I[v, v] = -1\n return I\n\ndef build_G(n:int, f):\n Zf = []\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n Zf.append(matrix_controlled_z(n, rep))\n\n # O_f^\\pm\n Zf = reduce(np.multiply, Zf, np.identity(2 ** n))\n\n return Zf\n\ndef make_circuit(n:int,f)-> Program:\n\n prog = Program() # circuit begin\n\n prog += H(0) # number=1\n prog += H(1) # number=4\n prog += H(2) # number=5\n prog += H(3) # number=6\n repeat = floor(sqrt(2 ** n) * pi / 4)\n\n for i in range(repeat):\n prog.defgate(\"Zf\",build_G(n,f))\n prog.inst((\"Zf\", *[i for i in range(n)]))\n prog += H(0) # number=3\n prog += H(1) # number=2\n prog += H(2) # number=7\n prog += H(3) # number=8\n\n prog += X(0) # number=9\n prog += X(1) # number=10\n prog += X(2) # number=11\n prog += X(3) # number=12\n\n prog += Z(0).controlled([1, 2, 3])\n prog += X(0) # number=13\n prog += X(1) # number=14\n prog += X(2) # number=15\n prog += X(3) # number=16\n\n prog += H(0) # number=17\n prog += H(1) # number=18\n prog += H(2) # number=19\n prog += H(3) # number=20\n\n\n # circuit end\n\n return prog\n\ndef summrise_results(bitstrings) -> dict:\n d = {}\n for l in bitstrings:\n if d.get(l) is None:\n d[l] = 1\n else:\n d[l] = d[l] + 1\n\n return d\n\nif __name__ == '__main__':\n\n x_bits = \"1011\"\n f = lambda rep: str(int(rep == x_bits))\n\n prog = make_circuit(4,f)\n print(list_quantum_computers(qpus=False))\n qvm = get_qc('9q-square-qvm')\n qvm.compiler.client.rpc_timeout = 60\n\n results = qvm.run_and_measure(prog,1024)\n bitstrings = np.vstack([results[i] for i in qvm.qubits()]).T\n bitstrings = [''.join(map(str, l)) for l in bitstrings]\n #writefile = open(\"../data/startPyquil9.csv\",\"w\")\n print(summrise_results(bitstrings))#,file=writefile)\n #writefile.close()\n\n", "# qubit number=3\n# total number=45\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class237.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=41\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[4]) # number=27\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=31\n prog.x(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.y(input_qubit[1]) # number=26\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[2]) # number=34\n prog.h(input_qubit[2]) # number=37\n prog.cz(input_qubit[4],input_qubit[2]) # number=35\n prog.h(input_qubit[2]) # number=36\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy918.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=48\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.z(input_qubit[1]) # number=30\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.x(input_qubit[3]) # number=46\n prog.y(input_qubit[1]) # number=47\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1145.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=63\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.x(input_qubit[4]) # number=53\n prog.cx(input_qubit[2],input_qubit[0]) # number=45\n prog.z(input_qubit[2]) # number=46\n prog.h(input_qubit[0]) # number=54\n prog.cz(input_qubit[2],input_qubit[0]) # number=55\n prog.h(input_qubit[0]) # number=56\n prog.h(input_qubit[1]) # number=4\n prog.rx(2.664070570244145,input_qubit[1]) # number=39\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[2]) # number=49\n prog.cz(input_qubit[3],input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=51\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[3]) # number=40\n prog.y(input_qubit[4]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=25\n prog.cz(input_qubit[1],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=36\n prog.cz(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=38\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[0]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.cx(input_qubit[2],input_qubit[3]) # number=44\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n prog.h(input_qubit[0]) # number=60\n prog.cz(input_qubit[1],input_qubit[0]) # number=61\n prog.h(input_qubit[0]) # number=62\n prog.z(input_qubit[1]) # number=58\n prog.cx(input_qubit[1],input_qubit[0]) # number=59\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1868.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=9\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[1]) # number=2\n prog.x(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[0]) # number=7\n prog.y(input_qubit[0]) # number=8\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy144.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=64\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC357.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.cx(input_qubit[0],input_qubit[1]) # number=47\n prog.x(input_qubit[1]) # number=48\n prog.cx(input_qubit[0],input_qubit[1]) # number=49\n prog.cx(input_qubit[0],input_qubit[1]) # number=42\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1090.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=32\n prog.cz(input_qubit[0],input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n prog.x(input_qubit[3]) # number=38\n prog.cx(input_qubit[0],input_qubit[3]) # number=39\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=29\n prog.cz(input_qubit[0],input_qubit[2]) # number=30\n prog.h(input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.y(input_qubit[3]) # number=36\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.z(input_qubit[1]) # number=35\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[3],input_qubit[0]) # number=13\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2436.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=41\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[4]) # number=27\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[4]) # number=34\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.y(input_qubit[1]) # number=26\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[2]) # number=31\n prog.cz(input_qubit[4],input_qubit[2]) # number=32\n prog.h(input_qubit[2]) # number=33\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class931.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=7\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=2\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[0]) # number=3\n prog.x(input_qubit[0]) # number=4\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.cx(input_qubit[1],input_qubit[0]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit61.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[0],input_qubit[2]) # number=7\n prog.x(input_qubit[2]) # number=8\n prog.cx(input_qubit[0],input_qubit[2]) # number=9\n prog.x(input_qubit[2]) # number=6\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC36.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=41\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.y(input_qubit[1]) # number=37\n prog.h(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[3],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.z(input_qubit[3]) # number=27\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[2]) # number=36\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2803.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.33300882128051834,input_qubit[2]) # number=36\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[3],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n prog.z(input_qubit[3]) # number=24\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2566.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=29\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class159.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=10\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6\n c.append(cirq.Y.on(input_qubit[3])) # number=8\n c.append(cirq.Y.on(input_qubit[3])) # number=9\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =0\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class68.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=5\n# total number=59\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[4],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=56\n prog.cz(input_qubit[4],input_qubit[0]) # number=57\n prog.h(input_qubit[0]) # number=58\n prog.z(input_qubit[4]) # number=47\n prog.cx(input_qubit[4],input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[4],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(-1.0430087609918113,input_qubit[4]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=52\n prog.x(input_qubit[0]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=54\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.x(input_qubit[1]) # number=10\n prog.rx(-0.06597344572538572,input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.h(input_qubit[4]) # number=35\n\n\n prog.h(input_qubit[0]) # number=17\n prog.rx(2.4912829742967055,input_qubit[2]) # number=26\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1691.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[1]) # number=31\n prog.cz(input_qubit[2],input_qubit[1]) # number=32\n prog.h(input_qubit[1]) # number=33\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=24\n prog.cz(input_qubit[3],input_qubit[0]) # number=25\n prog.h(input_qubit[0]) # number=26\n prog.cx(input_qubit[3],input_qubit[0]) # number=28\n prog.z(input_qubit[3]) # number=29\n prog.cx(input_qubit[3],input_qubit[0]) # number=30\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.x(input_qubit[2]) # number=38\n prog.cx(input_qubit[0],input_qubit[2]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2782.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=12\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=6\n prog.cz(input_qubit[0],input_qubit[1]) # number=7\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=8\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.cx(input_qubit[1],input_qubit[0]) # number=11\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC212.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=12\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=6\n prog.cz(input_qubit[0],input_qubit[1]) # number=7\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=8\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.swap(input_qubit[1],input_qubit[0]) # number=10\n prog.swap(input_qubit[1],input_qubit[0]) # number=11\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit207.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=8\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.x(input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_QC21.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=22\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class123.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.rx(-0.1602212253330796,input_qubit[1]) # number=36\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.x(input_qubit[0]) # number=9\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.h(input_qubit[4]) # number=31\n prog.x(input_qubit[1]) # number=29\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.x(input_qubit[2]) # number=26\n prog.cx(input_qubit[0],input_qubit[2]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=24\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.z(input_qubit[1]) # number=34\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class839.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=43\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=40\n prog.cz(input_qubit[0],input_qubit[3]) # number=41\n prog.h(input_qubit[3]) # number=42\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.y(input_qubit[1]) # number=37\n prog.h(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=32\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.z(input_qubit[3]) # number=27\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[2]) # number=36\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.y(input_qubit[2]) # number=38\n prog.y(input_qubit[2]) # number=39\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class3062.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=10\n prog.h(input_qubit[3]) # number=40\n prog.cz(input_qubit[0],input_qubit[3]) # number=41\n prog.h(input_qubit[3]) # number=42\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=21\n prog.h(input_qubit[2]) # number=36\n prog.cz(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=38\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[2]) # number=39\n\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[3],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n prog.y(input_qubit[2]) # number=29\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2969.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=12\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=6\n prog.cz(input_qubit[0],input_qubit[1]) # number=7\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=8\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.x(input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy208.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=71\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=70\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class403.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=7\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_noisy12.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=45\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[1],input_qubit[2]) # number=38\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=39\n prog.cz(input_qubit[1],input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=41\n prog.h(input_qubit[0]) # number=31\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.x(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[1],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.x(input_qubit[2]) # number=26\n prog.cx(input_qubit[0],input_qubit[2]) # number=27\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[4]) # number=42\n prog.cz(input_qubit[2],input_qubit[4]) # number=43\n prog.h(input_qubit[4]) # number=44\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy954.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=17\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=5\n c.append(cirq.H.on(input_qubit[0])) # number=12\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=13\n c.append(cirq.H.on(input_qubit[0])) # number=14\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10\n c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11\n c.append(cirq.Y.on(input_qubit[1])) # number=15\n c.append(cirq.Y.on(input_qubit[1])) # number=16\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =2820\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class387.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=5\n# total number=41\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(1):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[4]) # number=27\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[4]) # number=34\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.y(input_qubit[1]) # number=26\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[2]) # number=31\n prog.cz(input_qubit[4],input_qubit[2]) # number=32\n prog.h(input_qubit[2]) # number=33\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n prog.h(input_qubit[0]) \n prog.h(input_qubit[1])\n prog.h(input_qubit[2])\n prog.h(input_qubit[3])\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC933.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=5\n prog.h(input_qubit[0]) # number=7\n prog.cz(input_qubit[1],input_qubit[0]) # number=8\n prog.h(input_qubit[0]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit61.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.y(input_qubit[1]) # number=37\n prog.h(input_qubit[3]) # number=25\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=32\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.z(input_qubit[3]) # number=27\n prog.h(input_qubit[0]) # number=29\n prog.cz(input_qubit[3],input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.h(input_qubit[0]) # number=35\n prog.h(input_qubit[2]) # number=36\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=38\n prog.y(input_qubit[1]) # number=39\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2807.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=21\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n prog.cx(input_qubit[1],input_qubit[0]) # number=18\n prog.x(input_qubit[0]) # number=19\n prog.cx(input_qubit[1],input_qubit[0]) # number=20\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n prog.x(input_qubit[0]) # number=16\n prog.x(input_qubit[0]) # number=17\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit365.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=46\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=23\n prog.rx(-0.6848671984825748,input_qubit[1]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=40\n prog.x(input_qubit[3]) # number=41\n prog.cx(input_qubit[0],input_qubit[3]) # number=42\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.z(input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[0]) # number=45\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[3],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.h(input_qubit[1]) # number=36\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC3054.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=45\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.cx(input_qubit[0],input_qubit[2]) # number=35\n prog.x(input_qubit[2]) # number=36\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy239.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=23\n prog.rx(-0.6848671984825748,input_qubit[1]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=31\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[3],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n prog.z(input_qubit[3]) # number=21\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[3],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.h(input_qubit[1]) # number=36\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2536.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=47\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.cx(input_qubit[3],input_qubit[0]) # number=32\n prog.cx(input_qubit[3],input_qubit[0]) # number=44\n prog.z(input_qubit[3]) # number=45\n prog.cx(input_qubit[3],input_qubit[0]) # number=46\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.11938052083641225,input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(1.4765485471872026,input_qubit[2]) # number=35\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=41\n prog.x(input_qubit[0]) # number=42\n prog.cx(input_qubit[1],input_qubit[0]) # number=43\n prog.x(input_qubit[4]) # number=30\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(0.45238934211692994,input_qubit[3]) # number=38\n prog.y(input_qubit[1]) # number=39\n prog.rx(-2.5258404934861938,input_qubit[1]) # number=25\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=23\n prog.cx(input_qubit[0],input_qubit[3]) # number=24\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.rx(-0.0722566310325653,input_qubit[4]) # number=37\n prog.x(input_qubit[1]) # number=14\n prog.cx(input_qubit[0],input_qubit[2]) # number=26\n prog.x(input_qubit[2]) # number=27\n prog.h(input_qubit[4]) # number=40\n prog.cx(input_qubit[0],input_qubit[2]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1476.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.z(input_qubit[1]) # number=30\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=47\n prog.cz(input_qubit[3],input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=49\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.x(input_qubit[3]) # number=46\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1149.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=21\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n prog.x(input_qubit[0]) # number=8\n prog.h(input_qubit[0]) # number=18\n prog.cz(input_qubit[1],input_qubit[0]) # number=19\n prog.h(input_qubit[0]) # number=20\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n prog.x(input_qubit[0]) # number=16\n prog.x(input_qubit[0]) # number=17\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC349.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.y(input_qubit[2]) # number=8\n prog.y(input_qubit[2]) # number=9\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC330.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=60\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.cx(input_qubit[1],input_qubit[0]) # number=52\n prog.z(input_qubit[1]) # number=53\n prog.cx(input_qubit[1],input_qubit[0]) # number=54\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[1],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[4]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.h(input_qubit[1]) # number=56\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.rx(-2.9845130209103035,input_qubit[4]) # number=55\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1617.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=33\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=20\n prog.cz(input_qubit[0],input_qubit[3]) # number=21\n prog.h(input_qubit[3]) # number=22\n prog.x(input_qubit[3]) # number=13\n prog.h(input_qubit[3]) # number=23\n prog.cz(input_qubit[0],input_qubit[3]) # number=24\n prog.h(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.y(input_qubit[2]) # number=18\n prog.z(input_qubit[3]) # number=28\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[1]) # number=19\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[2],input_qubit[0]) # number=16\n prog.h(input_qubit[0]) # number=17\n prog.y(input_qubit[1]) # number=26\n prog.y(input_qubit[1]) # number=27\n prog.swap(input_qubit[1],input_qubit[0]) # number=29\n prog.swap(input_qubit[1],input_qubit[0]) # number=30\n prog.cx(input_qubit[2],input_qubit[0]) # number=31\n prog.cx(input_qubit[2],input_qubit[0]) # number=32\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2099.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 5/15/20 4:49 PM\n# @File : grover.py\n\n# qubit number=4\n# total number=19\nimport cirq\nimport cirq.google as cg\nfrom typing import Optional\nimport sys\nfrom math import log2\nimport numpy as np\n\n#thatsNoCode\n\ndef make_circuit(n: int, input_qubit):\n c = cirq.Circuit() # circuit begin\n\n c.append(cirq.H.on(input_qubit[0])) # number=1\n c.append(cirq.H.on(input_qubit[1])) # number=2\n c.append(cirq.H.on(input_qubit[1])) # number=7\n c.append(cirq.H.on(input_qubit[2])) # number=3\n c.append(cirq.H.on(input_qubit[3])) # number=4\n c.append(cirq.H.on(input_qubit[0])) # number=16\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=17\n c.append(cirq.H.on(input_qubit[0])) # number=18\n c.append(cirq.H.on(input_qubit[0])) # number=10\n c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=11\n c.append(cirq.H.on(input_qubit[0])) # number=12\n c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=8\n c.append(cirq.H.on(input_qubit[0])) # number=13\n c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) # number=14\n c.append(cirq.H.on(input_qubit[0])) # number=15\n # circuit end\n\n\n return c\n\ndef bitstring(bits):\n return ''.join(str(int(b)) for b in bits)\n\nif __name__ == '__main__':\n qubit_count = 4\n\n input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]\n circuit = make_circuit(qubit_count,input_qubits)\n circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')\n\n circuit_sample_count =0\n\n info = cirq.final_state_vector(circuit)\n\n qubits = round(log2(len(info)))\n frequencies = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n writefile = open(\"../data/startCirq_Class319.csv\",\"w+\")\n\n print(format(frequencies),file=writefile)\n print(\"results end\", file=writefile)\n\n print(circuit.__len__(), file=writefile)\n print(circuit,file=writefile)\n\n\n writefile.close()", "# qubit number=4\n# total number=40\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=24\n prog.cz(input_qubit[0],input_qubit[3]) # number=25\n prog.h(input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=21\n prog.cz(input_qubit[0],input_qubit[3]) # number=22\n prog.h(input_qubit[3]) # number=23\n prog.h(input_qubit[3]) # number=27\n prog.cz(input_qubit[0],input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=29\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n prog.x(input_qubit[3]) # number=38\n prog.cx(input_qubit[0],input_qubit[3]) # number=39\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=18\n prog.rx(-0.364424747816416,input_qubit[3]) # number=36\n prog.y(input_qubit[3]) # number=20\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=19\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2217.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.y(input_qubit[3]) # number=10\n prog.y(input_qubit[3]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_Class197.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=66\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[0]) # number=57\n prog.cz(input_qubit[4],input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=59\n prog.z(input_qubit[4]) # number=55\n prog.cx(input_qubit[4],input_qubit[0]) # number=56\n prog.h(input_qubit[2]) # number=50\n prog.cz(input_qubit[4],input_qubit[2]) # number=51\n prog.h(input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=63\n prog.cz(input_qubit[3],input_qubit[0]) # number=64\n prog.h(input_qubit[0]) # number=65\n prog.z(input_qubit[3]) # number=61\n prog.cx(input_qubit[3],input_qubit[0]) # number=62\n prog.cz(input_qubit[1],input_qubit[0]) # number=29\n prog.h(input_qubit[0]) # number=30\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[1],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[1],input_qubit[0]) # number=35\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=37\n prog.h(input_qubit[0]) # number=46\n prog.cz(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.y(input_qubit[2]) # number=41\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.rx(1.0398671683382215,input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit1762.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=49\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=46\n prog.cz(input_qubit[0],input_qubit[3]) # number=47\n prog.h(input_qubit[3]) # number=48\n prog.h(input_qubit[3]) # number=40\n prog.cz(input_qubit[0],input_qubit[3]) # number=41\n prog.h(input_qubit[3]) # number=42\n prog.h(input_qubit[3]) # number=43\n prog.cz(input_qubit[0],input_qubit[3]) # number=44\n prog.h(input_qubit[3]) # number=45\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=21\n prog.h(input_qubit[2]) # number=36\n prog.cz(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=38\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n prog.h(input_qubit[2]) # number=39\n\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[3],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n prog.y(input_qubit[2]) # number=29\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC3235.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=10\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.cz(input_qubit[3],input_qubit[2]) # number=8\n prog.h(input_qubit[2]) # number=9\n prog.z(input_qubit[3]) # number=5\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5200\n writefile = open(\"../data/startQiskit_noisy94.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=34\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.h(input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=11\n prog.h(input_qubit[3]) # number=13\n prog.cz(input_qubit[0],input_qubit[3]) # number=14\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[3],input_qubit[1]) # number=19\n prog.z(input_qubit[3]) # number=25\n prog.h(input_qubit[1]) # number=20\n prog.rx(-3.141592653589793,input_qubit[3]) # number=26\n prog.h(input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[2]) # number=17\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=27\n prog.cz(input_qubit[1],input_qubit[0]) # number=28\n prog.h(input_qubit[0]) # number=29\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.x(input_qubit[1]) # number=24\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2205.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=10\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.x(input_qubit[1]) # number=2\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[0],input_qubit[1]) # number=8\n prog.h(input_qubit[1]) # number=9\n prog.x(input_qubit[1]) # number=5\n prog.cx(input_qubit[0],input_qubit[1]) # number=6\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy61.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=77\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[1]) # number=70\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC429.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=51\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.cx(input_qubit[0],input_qubit[2]) # number=45\n prog.x(input_qubit[2]) # number=46\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.cx(input_qubit[0],input_qubit[2]) # number=33\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class254.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=12\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=6\n prog.cx(input_qubit[0],input_qubit[1]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[1]) # number=11\n prog.cx(input_qubit[0],input_qubit[1]) # number=8\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.x(input_qubit[1]) # number=2\n prog.x(input_qubit[1]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class161.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=28\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.z(input_qubit[3]) # number=35\n prog.cx(input_qubit[3],input_qubit[0]) # number=36\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.cx(input_qubit[2],input_qubit[0]) # number=10\n prog.h(input_qubit[0]) # number=14\n prog.h(input_qubit[1]) # number=30\n prog.cz(input_qubit[2],input_qubit[0]) # number=15\n prog.h(input_qubit[0]) # number=16\n prog.cx(input_qubit[0],input_qubit[2]) # number=20\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=17\n prog.cx(input_qubit[0],input_qubit[2]) # number=23\n prog.x(input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.cx(input_qubit[0],input_qubit[2]) # number=19\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2117.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.x(input_qubit[3]) # number=28\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.33300882128051834,input_qubit[2]) # number=36\n prog.h(input_qubit[0]) # number=35\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.z(input_qubit[3]) # number=24\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2298.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=13\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.cx(input_qubit[1],input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.h(input_qubit[3]) # number=10\n prog.cx(input_qubit[1],input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =5600\n writefile = open(\"../data/startQiskit_QC402.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.z(input_qubit[1]) # number=48\n prog.cx(input_qubit[1],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n prog.cx(input_qubit[3],input_qubit[2]) # number=45\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.x(input_qubit[3]) # number=46\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1150.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=49\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[0]) # number=43\n prog.cz(input_qubit[4],input_qubit[0]) # number=44\n prog.h(input_qubit[0]) # number=45\n prog.cx(input_qubit[4],input_qubit[0]) # number=46\n prog.z(input_qubit[4]) # number=47\n prog.cx(input_qubit[4],input_qubit[0]) # number=48\n prog.h(input_qubit[0]) # number=37\n prog.cz(input_qubit[4],input_qubit[0]) # number=38\n prog.h(input_qubit[0]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.rx(-1.0430087609918113,input_qubit[4]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=41\n prog.cx(input_qubit[1],input_qubit[0]) # number=42\n prog.x(input_qubit[1]) # number=10\n prog.rx(-0.06597344572538572,input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.x(input_qubit[2]) # number=23\n prog.h(input_qubit[2]) # number=28\n prog.cz(input_qubit[0],input_qubit[2]) # number=29\n prog.h(input_qubit[2]) # number=30\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n prog.h(input_qubit[4]) # number=35\n\n\n prog.h(input_qubit[0]) # number=17\n prog.rx(2.4912829742967055,input_qubit[2]) # number=26\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1236.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=37\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[0],input_qubit[3]) # number=17\n prog.rx(-0.5686282702997527,input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=18\n prog.h(input_qubit[3]) # number=26\n prog.cz(input_qubit[0],input_qubit[3]) # number=27\n prog.h(input_qubit[3]) # number=28\n prog.x(input_qubit[3]) # number=21\n prog.rx(0.4241150082346221,input_qubit[2]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=22\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=23\n prog.cz(input_qubit[1],input_qubit[2]) # number=24\n prog.h(input_qubit[2]) # number=25\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=34\n prog.cz(input_qubit[2],input_qubit[0]) # number=35\n prog.h(input_qubit[0]) # number=36\n prog.z(input_qubit[2]) # number=30\n prog.cx(input_qubit[2],input_qubit[0]) # number=31\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[0]) # number=14\n prog.y(input_qubit[0]) # number=15\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC2165.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=37\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[2]) # number=31\n prog.x(input_qubit[2]) # number=32\n prog.h(input_qubit[2]) # number=34\n prog.cz(input_qubit[0],input_qubit[2]) # number=35\n prog.h(input_qubit[2]) # number=36\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.h(input_qubit[1]) # number=24\n prog.z(input_qubit[2]) # number=3\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_QC195.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=43\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=37\n prog.cz(input_qubit[0],input_qubit[3]) # number=38\n prog.h(input_qubit[3]) # number=39\n prog.cx(input_qubit[0],input_qubit[3]) # number=40\n prog.x(input_qubit[3]) # number=41\n prog.cx(input_qubit[0],input_qubit[3]) # number=42\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.h(input_qubit[0]) # number=33\n prog.cz(input_qubit[3],input_qubit[0]) # number=34\n prog.rx(0.33300882128051834,input_qubit[2]) # number=36\n prog.h(input_qubit[0]) # number=35\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.z(input_qubit[3]) # number=24\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2824.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=47\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=31\n prog.cz(input_qubit[0],input_qubit[3]) # number=32\n prog.h(input_qubit[3]) # number=33\n prog.cx(input_qubit[0],input_qubit[3]) # number=44\n prog.x(input_qubit[3]) # number=45\n prog.cx(input_qubit[0],input_qubit[3]) # number=46\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[0],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.cx(input_qubit[3],input_qubit[0]) # number=38\n prog.z(input_qubit[3]) # number=39\n prog.cx(input_qubit[3],input_qubit[0]) # number=40\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[2],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.y(input_qubit[3]) # number=37\n prog.h(input_qubit[0]) # number=14\n prog.h(input_qubit[1]) # number=30\n prog.cz(input_qubit[2],input_qubit[0]) # number=15\n prog.h(input_qubit[0]) # number=16\n prog.cx(input_qubit[0],input_qubit[2]) # number=20\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.cx(input_qubit[0],input_qubit[2]) # number=17\n prog.cx(input_qubit[0],input_qubit[2]) # number=23\n prog.x(input_qubit[2]) # number=24\n prog.cx(input_qubit[0],input_qubit[2]) # number=25\n prog.cx(input_qubit[0],input_qubit[2]) # number=19\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit3157.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=35\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=13\n prog.cx(input_qubit[0],input_qubit[3]) # number=17\n prog.x(input_qubit[3]) # number=18\n prog.rx(-3.1101767270538954,input_qubit[1]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=19\n prog.cx(input_qubit[0],input_qubit[3]) # number=15\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[1]) # number=26\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.x(input_qubit[3]) # number=29\n prog.h(input_qubit[2]) # number=7\n prog.cx(input_qubit[3],input_qubit[0]) # number=20\n prog.cx(input_qubit[3],input_qubit[0]) # number=23\n prog.cx(input_qubit[3],input_qubit[0]) # number=32\n prog.z(input_qubit[3]) # number=33\n prog.cx(input_qubit[3],input_qubit[0]) # number=34\n prog.cx(input_qubit[3],input_qubit[0]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=22\n prog.h(input_qubit[3]) # number=8\n prog.z(input_qubit[3]) # number=28\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('qasm_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit2557.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=63\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.h(input_qubit[0]) # number=31\n prog.y(input_qubit[1]) # number=56\n prog.cz(input_qubit[1],input_qubit[0]) # number=32\n prog.h(input_qubit[1]) # number=52\n prog.h(input_qubit[0]) # number=33\n prog.h(input_qubit[1]) # number=44\n prog.cz(input_qubit[0],input_qubit[1]) # number=45\n prog.h(input_qubit[1]) # number=46\n prog.h(input_qubit[1]) # number=57\n prog.cz(input_qubit[0],input_qubit[1]) # number=58\n prog.h(input_qubit[1]) # number=59\n prog.cx(input_qubit[0],input_qubit[1]) # number=60\n prog.x(input_qubit[1]) # number=61\n prog.cx(input_qubit[0],input_qubit[1]) # number=62\n prog.cx(input_qubit[0],input_qubit[1]) # number=55\n prog.h(input_qubit[1]) # number=48\n prog.cz(input_qubit[0],input_qubit[1]) # number=49\n prog.h(input_qubit[1]) # number=50\n prog.x(input_qubit[0]) # number=26\n prog.cx(input_qubit[1],input_qubit[0]) # number=27\n prog.h(input_qubit[1]) # number=37\n prog.cz(input_qubit[0],input_qubit[1]) # number=38\n prog.h(input_qubit[1]) # number=39\n prog.x(input_qubit[1]) # number=35\n prog.cx(input_qubit[0],input_qubit[1]) # number=36\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[3]) # number=12\n prog.cx(input_qubit[3],input_qubit[2]) # number=43\n prog.cx(input_qubit[3],input_qubit[2]) # number=47\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.cx(input_qubit[0],input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[1]) # number=29\n prog.y(input_qubit[4]) # number=28\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[3]) # number=51\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1891.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=52\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.h(input_qubit[0]) # number=49\n prog.cz(input_qubit[1],input_qubit[0]) # number=50\n prog.h(input_qubit[0]) # number=51\n prog.z(input_qubit[1]) # number=46\n prog.cx(input_qubit[1],input_qubit[0]) # number=47\n prog.h(input_qubit[0]) # number=32\n prog.cz(input_qubit[1],input_qubit[0]) # number=33\n prog.h(input_qubit[0]) # number=34\n prog.x(input_qubit[4]) # number=48\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.cx(input_qubit[3],input_qubit[0]) # number=41\n prog.z(input_qubit[3]) # number=42\n prog.cx(input_qubit[3],input_qubit[0]) # number=43\n prog.cx(input_qubit[1],input_qubit[3]) # number=44\n\n\n prog.x(input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=36\n prog.cx(input_qubit[0],input_qubit[3]) # number=37\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1159.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=10\n prog.h(input_qubit[3]) # number=33\n prog.cz(input_qubit[0],input_qubit[3]) # number=34\n prog.h(input_qubit[3]) # number=35\n prog.x(input_qubit[3]) # number=24\n prog.cx(input_qubit[0],input_qubit[3]) # number=25\n prog.cx(input_qubit[0],input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=30\n prog.cz(input_qubit[0],input_qubit[2]) # number=31\n prog.h(input_qubit[2]) # number=32\n prog.x(input_qubit[2]) # number=21\n prog.cx(input_qubit[0],input_qubit[2]) # number=22\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.h(input_qubit[0]) # number=5\n prog.h(input_qubit[3]) # number=16\n prog.cz(input_qubit[1],input_qubit[3]) # number=17\n prog.h(input_qubit[3]) # number=18\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.h(input_qubit[0]) # number=26\n prog.cz(input_qubit[3],input_qubit[0]) # number=27\n prog.h(input_qubit[0]) # number=28\n prog.cx(input_qubit[3],input_qubit[0]) # number=14\n prog.y(input_qubit[2]) # number=29\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1930.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=68\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_Class374.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=68\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.rx(-0.09738937226128368,input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=33\n prog.y(input_qubit[2]) # number=56\n prog.cz(input_qubit[2],input_qubit[1]) # number=34\n prog.h(input_qubit[1]) # number=35\n prog.h(input_qubit[1]) # number=3\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy381.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=15\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.rx(2.0860175219836226,input_qubit[1]) # number=7\n prog.x(input_qubit[0]) # number=5\n prog.x(input_qubit[0]) # number=6\n prog.h(input_qubit[0]) # number=10\n prog.cz(input_qubit[1],input_qubit[0]) # number=11\n prog.h(input_qubit[0]) # number=12\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.x(input_qubit[1]) # number=13\n prog.x(input_qubit[1]) # number=14\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = BasicAer.get_backend('statevector_simulator')\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n prog = circuit1\n\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n\n writefile = open(\"../data/startQiskit_Class268.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=18\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.y(input_qubit[1]) # number=2\n prog.y(input_qubit[1]) # number=4\n prog.y(input_qubit[1]) # number=3\n prog.h(input_qubit[0]) # number=13\n prog.cz(input_qubit[1],input_qubit[0]) # number=14\n prog.h(input_qubit[0]) # number=15\n prog.x(input_qubit[0]) # number=8\n prog.cx(input_qubit[1],input_qubit[0]) # number=9\n prog.cx(input_qubit[1],input_qubit[0]) # number=10\n prog.x(input_qubit[0]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=12\n prog.x(input_qubit[0]) # number=16\n prog.x(input_qubit[0]) # number=17\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n backend = FakeVigo()\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_noisy291.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=14\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.x(input_qubit[2]) # number=2\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.h(input_qubit[1]) # number=9\n prog.cx(input_qubit[2],input_qubit[1]) # number=4\n prog.h(input_qubit[1]) # number=11\n prog.cz(input_qubit[2],input_qubit[1]) # number=12\n prog.h(input_qubit[1]) # number=13\n prog.z(input_qubit[2]) # number=3\n prog.y(input_qubit[2]) # number=5\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit81.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = BasicAer.get_backend('qasm_simulator')\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=14\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.x(input_qubit[2]) # number=6\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.h(input_qubit[1]) # number=11\n prog.swap(input_qubit[1],input_qubit[0]) # number=8\n prog.y(input_qubit[0]) # number=9\n prog.y(input_qubit[0]) # number=10\n prog.x(input_qubit[1]) # number=12\n prog.x(input_qubit[1]) # number=13\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_QC730.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_5_yorktown\")\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=2\n# total number=12\nimport cirq\nimport qiskit\n\nfrom qiskit import IBMQ\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename='circuit/deutsch-oracle.png')\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n\n input_qubit = QuantumRegister(n, \"qc\")\n target = QuantumRegister(1, \"qt\")\n prog = QuantumCircuit(input_qubit, target)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(target)\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n\n prog.h(input_qubit[1]) # number=1\n prog.cx(input_qubit[0],input_qubit[1]) # number=6\n prog.x(input_qubit[1]) # number=7\n prog.cx(input_qubit[0],input_qubit[1]) # number=8\n prog.cx(input_qubit[0],input_qubit[1]) # number=4\n prog.h(target)\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [target])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n #for i in range(n):\n # prog.measure(input_qubit[i], classicals[i])\n\n prog.cx(input_qubit[0],input_qubit[1]) # number=9\n prog.x(input_qubit[1]) # number=10\n prog.cx(input_qubit[0],input_qubit[1]) # number=11\n prog.x(input_qubit[1]) # number=3\n # circuit end\n return prog\n\n\n\n\nif __name__ == '__main__':\n n = 2\n f = lambda rep: rep[-1]\n # f = lambda rep: \"1\" if rep[0:2] == \"01\" or rep[0:2] == \"10\" else \"0\"\n # f = lambda rep: \"0\"\n prog = make_circuit(n, f)\n sample_shot =2800\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = provider.get_backend(\"ibmq_belem\")\n\n circuit1 = transpile(prog,FakeVigo())\n circuit1.x(qubit=3)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n prog = circuit1\n\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n\n writefile = open(\"../data/startQiskit_QC170.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=36\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[3]) # number=30\n prog.cz(input_qubit[0],input_qubit[3]) # number=31\n prog.h(input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=33\n prog.x(input_qubit[3]) # number=34\n prog.cx(input_qubit[0],input_qubit[3]) # number=35\n prog.cx(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=13\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[1],input_qubit[0]) # number=16\n prog.h(input_qubit[1]) # number=20\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[3],input_qubit[0]) # number=24\n prog.z(input_qubit[3]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=21\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[2],input_qubit[0]) # number=22\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = FakeVigo()\n sample_shot =8000\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy2573.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=77\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\n\ndef build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n # oracle.draw('mpl', filename=(kernel + '-oracle.png'))\n return oracle\n\n\ndef build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:\n # implement the Bernstein-Vazirani circuit\n zero = np.binary_repr(0, n)\n b = f(zero)\n\n # initial n + 1 bits\n input_qubit = QuantumRegister(n+1, \"qc\")\n classicals = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classicals)\n\n # inverse last one (can be omitted if using O_f^\\pm)\n prog.x(input_qubit[n])\n # circuit begin\n prog.h(input_qubit[1]) # number=1\n prog.h(input_qubit[2]) # number=38\n prog.cz(input_qubit[0],input_qubit[2]) # number=39\n prog.h(input_qubit[2]) # number=40\n prog.h(input_qubit[2]) # number=59\n prog.cz(input_qubit[0],input_qubit[2]) # number=60\n prog.h(input_qubit[2]) # number=61\n prog.h(input_qubit[2]) # number=42\n prog.cz(input_qubit[0],input_qubit[2]) # number=43\n prog.h(input_qubit[2]) # number=44\n prog.h(input_qubit[2]) # number=48\n prog.cz(input_qubit[0],input_qubit[2]) # number=49\n prog.h(input_qubit[2]) # number=50\n prog.h(input_qubit[2]) # number=71\n prog.cz(input_qubit[0],input_qubit[2]) # number=72\n prog.h(input_qubit[2]) # number=73\n prog.x(input_qubit[2]) # number=55\n prog.h(input_qubit[2]) # number=67\n prog.cz(input_qubit[0],input_qubit[2]) # number=68\n prog.h(input_qubit[2]) # number=69\n prog.h(input_qubit[2]) # number=64\n prog.cz(input_qubit[0],input_qubit[2]) # number=65\n prog.h(input_qubit[2]) # number=66\n prog.cx(input_qubit[0],input_qubit[2]) # number=37\n prog.h(input_qubit[2]) # number=51\n prog.cz(input_qubit[0],input_qubit[2]) # number=52\n prog.h(input_qubit[2]) # number=53\n prog.h(input_qubit[2]) # number=25\n prog.cz(input_qubit[0],input_qubit[2]) # number=26\n prog.h(input_qubit[2]) # number=27\n prog.h(input_qubit[1]) # number=7\n prog.cz(input_qubit[2],input_qubit[1]) # number=8\n prog.rx(0.17592918860102857,input_qubit[2]) # number=34\n prog.rx(-0.3989822670059037,input_qubit[1]) # number=30\n prog.h(input_qubit[1]) # number=9\n prog.h(input_qubit[1]) # number=18\n prog.rx(2.3310617489636263,input_qubit[2]) # number=58\n prog.cz(input_qubit[2],input_qubit[1]) # number=19\n prog.h(input_qubit[1]) # number=20\n prog.x(input_qubit[1]) # number=62\n prog.y(input_qubit[1]) # number=14\n prog.h(input_qubit[1]) # number=22\n prog.cz(input_qubit[2],input_qubit[1]) # number=23\n prog.rx(-0.9173450548482197,input_qubit[1]) # number=57\n prog.cx(input_qubit[2],input_qubit[1]) # number=63\n prog.h(input_qubit[1]) # number=24\n prog.cx(input_qubit[2],input_qubit[0]) # number=74\n prog.z(input_qubit[2]) # number=75\n prog.cx(input_qubit[2],input_qubit[0]) # number=76\n prog.cx(input_qubit[2],input_qubit[1]) # number=70\n prog.z(input_qubit[1]) # number=41\n prog.x(input_qubit[1]) # number=17\n prog.y(input_qubit[2]) # number=5\n prog.x(input_qubit[2]) # number=21\n\n # apply H to get superposition\n for i in range(n):\n prog.h(input_qubit[i])\n prog.h(input_qubit[n])\n prog.barrier()\n\n # apply oracle O_f\n oracle = build_oracle(n, f)\n prog.append(\n oracle.to_gate(),\n [input_qubit[i] for i in range(n)] + [input_qubit[n]])\n\n # apply H back (QFT on Z_2^n)\n for i in range(n):\n prog.h(input_qubit[i])\n prog.barrier()\n\n # measure\n\n return prog\n\n\ndef get_statevector(prog: QuantumCircuit) -> Any:\n state_backend = Aer.get_backend('statevector_simulator')\n statevec = execute(prog, state_backend).result()\n quantum_state = statevec.get_statevector()\n qubits = round(log2(len(quantum_state)))\n quantum_state = {\n \"|\" + np.binary_repr(i, qubits) + \">\": quantum_state[i]\n for i in range(2 ** qubits)\n }\n return quantum_state\n\n\ndef evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:\n # Q: which backend should we use?\n\n # get state vector\n quantum_state = get_statevector(prog)\n\n # get simulate results\n\n # provider = IBMQ.load_account()\n # backend = provider.get_backend(backend_str)\n # qobj = compile(prog, backend, shots)\n # job = backend.run(qobj)\n # job.result()\n backend = Aer.get_backend(backend_str)\n # transpile/schedule -> assemble -> backend.run\n results = execute(prog, backend, shots=shots).result()\n counts = results.get_counts()\n a = Counter(counts).most_common(1)[0][0][::-1]\n\n return {\n \"measurements\": counts,\n # \"state\": statevec,\n \"quantum_state\": quantum_state,\n \"a\": a,\n \"b\": b\n }\n\n\ndef bernstein_test_1(rep: str):\n \"\"\"011 . x + 1\"\"\"\n a = \"011\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_2(rep: str):\n \"\"\"000 . x + 0\"\"\"\n a = \"000\"\n b = \"0\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\ndef bernstein_test_3(rep: str):\n \"\"\"111 . x + 1\"\"\"\n a = \"111\"\n b = \"1\"\n return bitwise_xor(bitwise_dot(a, rep), b)\n\n\nif __name__ == \"__main__\":\n n = 2\n a = \"11\"\n b = \"1\"\n f = lambda rep: \\\n bitwise_xor(bitwise_dot(a, rep), b)\n prog = build_circuit(n, f)\n sample_shot =4000\n writefile = open(\"../data/startQiskit_noisy387.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.h(qubit=2)\n circuit1.x(qubit=3)\n circuit1.measure_all()\n\n info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=4\n# total number=33\nimport cirq\nimport qiskit\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2\nimport numpy as np\nimport networkx as nx\n\ndef bitwise_xor(s: str, t: str) -> str:\n length = len(s)\n res = []\n for i in range(length):\n res.append(str(int(s[i]) ^ int(t[i])))\n return ''.join(res[::-1])\n\n\ndef bitwise_dot(s: str, t: str) -> str:\n length = len(s)\n res = 0\n for i in range(length):\n res += int(s[i]) * int(t[i])\n return str(res % 2)\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f\n # NOTE: use multi_control_toffoli_gate ('noancilla' mode)\n # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html\n # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates\n # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate\n controls = QuantumRegister(n, \"ofc\")\n target = QuantumRegister(1, \"oft\")\n oracle = QuantumCircuit(controls, target, name=\"Of\")\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n oracle.mct(controls, target[0], None, mode='noancilla')\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n return oracle\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.cx(input_qubit[0],input_qubit[3]) # number=27\n prog.cx(input_qubit[0],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=31\n prog.cx(input_qubit[0],input_qubit[3]) # number=32\n prog.cx(input_qubit[0],input_qubit[3]) # number=29\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=12\n prog.h(input_qubit[0]) # number=5\n\n oracle = build_oracle(n-1, f)\n prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])\n prog.h(input_qubit[1]) # number=6\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=9\n\n prog.y(input_qubit[2]) # number=10\n prog.y(input_qubit[2]) # number=11\n prog.cx(input_qubit[1],input_qubit[0]) # number=13\n prog.h(input_qubit[0]) # number=15\n prog.cz(input_qubit[1],input_qubit[0]) # number=16\n prog.h(input_qubit[1]) # number=20\n prog.h(input_qubit[2]) # number=19\n prog.cx(input_qubit[3],input_qubit[0]) # number=24\n prog.z(input_qubit[3]) # number=25\n prog.cx(input_qubit[3],input_qubit[0]) # number=26\n prog.h(input_qubit[0]) # number=17\n prog.cx(input_qubit[2],input_qubit[0]) # number=21\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[2],input_qubit[0]) # number=22\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n a = \"111\"\n b = \"0\"\n f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)\n prog = make_circuit(4,f)\n backend = BasicAer.get_backend('statevector_simulator')\n sample_shot =8000\n\n info = execute(prog, backend=backend).result().get_statevector()\n qubits = round(log2(len(info)))\n info = {\n np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)\n for i in range(2 ** qubits)\n }\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_Class2317.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.__len__(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=3\n# total number=12\n\nimport numpy as np\n\nfrom qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ\nimport networkx as nx\nfrom qiskit.visualization import plot_histogram\nfrom typing import *\nfrom pprint import pprint\nfrom math import log2\nfrom collections import Counter\nfrom qiskit.test.mock import FakeVigo, FakeYorktown\n\nkernel = 'circuit/bernstein'\n\n\ndef make_circuit(n:int) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n prog = QuantumCircuit(input_qubit)\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=3\n prog.h(input_qubit[3]) # number=4\n prog.y(input_qubit[3]) # number=5\n\n for edge in E:\n k = edge[0]\n l = edge[1]\n prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])\n prog.p(gamma, k)\n prog.p(gamma, l)\n\n prog.rx(2 * beta, range(len(V)))\n\n prog.swap(input_qubit[1],input_qubit[0]) # number=6\n prog.swap(input_qubit[1],input_qubit[0]) # number=7\n prog.x(input_qubit[0]) # number=8\n prog.x(input_qubit[0]) # number=9\n prog.y(input_qubit[1]) # number=10\n prog.y(input_qubit[1]) # number=11\n # circuit end\n\n\n\n return prog\n\n\n\nif __name__ == '__main__':\n n = 4\n V = np.arange(0, n, 1)\n E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]\n\n G = nx.Graph()\n G.add_nodes_from(V)\n G.add_weighted_edges_from(E)\n\n step_size = 0.1\n\n a_gamma = np.arange(0, np.pi, step_size)\n a_beta = np.arange(0, np.pi, step_size)\n a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)\n\n F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (\n 1 + np.cos(4 * a_gamma) ** 2)\n\n result = np.where(F1 == np.amax(F1))\n a = list(zip(result[0], result[1]))[0]\n\n gamma = a[0] * step_size\n beta = a[1] * step_size\n\n prog = make_circuit(4)\n sample_shot =3962\n writefile = open(\"../data/startQiskit_noisy343.csv\", \"w\")\n # prog.draw('mpl', filename=(kernel + '.png'))\n backend = FakeYorktown()\n\n circuit1 = transpile(prog, FakeYorktown())\n circuit1.measure_all()\n prog = circuit1\n\n info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()\n\n print(info, file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(), file=writefile)\n print(circuit1, file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=49\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[1]) # number=26\n prog.cz(input_qubit[4],input_qubit[1]) # number=27\n prog.h(input_qubit[1]) # number=28\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n prog.h(input_qubit[1]) # number=34\n prog.cz(input_qubit[4],input_qubit[1]) # number=35\n prog.rx(0.8011061266653969,input_qubit[2]) # number=37\n prog.h(input_qubit[1]) # number=36\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=38\n prog.x(input_qubit[0]) # number=39\n prog.cx(input_qubit[1],input_qubit[0]) # number=40\n prog.h(input_qubit[1]) # number=46\n prog.cz(input_qubit[0],input_qubit[1]) # number=47\n prog.h(input_qubit[1]) # number=48\n prog.x(input_qubit[1]) # number=43\n prog.cx(input_qubit[0],input_qubit[1]) # number=44\n prog.x(input_qubit[2]) # number=11\n prog.y(input_qubit[1]) # number=45\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=41\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=22\n prog.x(input_qubit[0]) # number=23\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.cx(input_qubit[0],input_qubit[1]) # number=30\n prog.x(input_qubit[1]) # number=31\n prog.cx(input_qubit[0],input_qubit[1]) # number=32\n prog.x(input_qubit[2]) # number=15\n prog.h(input_qubit[4]) # number=29\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1221.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=50\nimport cirq\nimport qiskit\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.rx(-1.3603096190043806,input_qubit[2]) # number=28\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[4]) # number=21\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[3]) # number=34\n prog.cz(input_qubit[4],input_qubit[3]) # number=35\n prog.h(input_qubit[3]) # number=36\n\n\n prog.h(input_qubit[0]) # number=38\n prog.cz(input_qubit[1],input_qubit[0]) # number=39\n prog.h(input_qubit[0]) # number=40\n prog.x(input_qubit[0]) # number=32\n prog.cx(input_qubit[1],input_qubit[0]) # number=33\n prog.cx(input_qubit[0],input_qubit[1]) # number=24\n prog.x(input_qubit[1]) # number=25\n prog.x(input_qubit[1]) # number=41\n prog.cx(input_qubit[0],input_qubit[1]) # number=26\n prog.x(input_qubit[2]) # number=11\n prog.cx(input_qubit[2],input_qubit[3]) # number=30\n prog.x(input_qubit[3]) # number=12\n prog.h(input_qubit[2]) # number=42\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.x(input_qubit[0]) # number=13\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[4]) # number=46\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[0],input_qubit[2]) # number=43\n prog.cx(input_qubit[0],input_qubit[2]) # number=47\n prog.x(input_qubit[2]) # number=48\n prog.cx(input_qubit[0],input_qubit[2]) # number=49\n prog.cx(input_qubit[0],input_qubit[2]) # number=45\n prog.rx(-1.9697785938008003,input_qubit[1]) # number=37\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.x(input_qubit[1]) # number=23\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n IBMQ.load_account() \n provider = IBMQ.get_provider(hub='ibm-q') \n provider.backends()\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_QC1367.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n", "# qubit number=5\n# total number=62\nimport cirq\nimport qiskit\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.test.mock import FakeVigo\n\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit import BasicAer, execute, transpile\nfrom pprint import pprint\nfrom qiskit.test.mock import FakeVigo\nfrom math import log2,floor, sqrt, pi\nimport numpy as np\nimport networkx as nx\n\ndef build_oracle(n: int, f) -> QuantumCircuit:\n # implement the oracle O_f^\\pm\n # NOTE: use U1 gate (P gate) with \\lambda = 180 ==> CZ gate\n # or multi_control_Z_gate (issue #127)\n\n controls = QuantumRegister(n, \"ofc\")\n oracle = QuantumCircuit(controls, name=\"Zf\")\n\n for i in range(2 ** n):\n rep = np.binary_repr(i, n)\n if f(rep) == \"1\":\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n\n # oracle.h(controls[n])\n if n >= 2:\n oracle.mcu1(pi, controls[1:], controls[0])\n\n for j in range(n):\n if rep[j] == \"0\":\n oracle.x(controls[j])\n # oracle.barrier()\n\n return oracle\n\n\ndef make_circuit(n:int,f) -> QuantumCircuit:\n # circuit begin\n input_qubit = QuantumRegister(n,\"qc\")\n classical = ClassicalRegister(n, \"qm\")\n prog = QuantumCircuit(input_qubit, classical)\n prog.h(input_qubit[0]) # number=3\n prog.h(input_qubit[1]) # number=4\n prog.h(input_qubit[2]) # number=5\n prog.h(input_qubit[3]) # number=6\n prog.h(input_qubit[0]) # number=41\n prog.cz(input_qubit[1],input_qubit[0]) # number=42\n prog.h(input_qubit[0]) # number=43\n prog.z(input_qubit[1]) # number=37\n prog.h(input_qubit[0]) # number=51\n prog.cz(input_qubit[1],input_qubit[0]) # number=52\n prog.h(input_qubit[0]) # number=53\n prog.h(input_qubit[4]) # number=21\n prog.x(input_qubit[2]) # number=39\n\n Zf = build_oracle(n, f)\n\n repeat = floor(sqrt(2 ** n) * pi / 4)\n for i in range(repeat):\n prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)])\n prog.h(input_qubit[0]) # number=1\n prog.h(input_qubit[1]) # number=2\n prog.h(input_qubit[2]) # number=7\n prog.h(input_qubit[3]) # number=8\n prog.h(input_qubit[0]) # number=56\n prog.cz(input_qubit[3],input_qubit[0]) # number=57\n prog.h(input_qubit[0]) # number=58\n prog.h(input_qubit[0]) # number=48\n prog.cz(input_qubit[3],input_qubit[0]) # number=49\n prog.h(input_qubit[0]) # number=50\n prog.z(input_qubit[3]) # number=46\n prog.h(input_qubit[0]) # number=59\n prog.cz(input_qubit[3],input_qubit[0]) # number=60\n prog.h(input_qubit[0]) # number=61\n prog.x(input_qubit[4]) # number=40\n prog.cx(input_qubit[3],input_qubit[0]) # number=35\n\n\n prog.x(input_qubit[0]) # number=9\n prog.cx(input_qubit[0],input_qubit[1]) # number=29\n prog.x(input_qubit[1]) # number=30\n prog.cx(input_qubit[0],input_qubit[1]) # number=31\n prog.x(input_qubit[2]) # number=11\n prog.x(input_qubit[1]) # number=44\n prog.x(input_qubit[3]) # number=12\n\n if n>=2:\n prog.mcu1(pi,input_qubit[1:],input_qubit[0])\n\n prog.cx(input_qubit[1],input_qubit[0]) # number=24\n prog.x(input_qubit[0]) # number=25\n prog.cx(input_qubit[1],input_qubit[0]) # number=26\n prog.x(input_qubit[1]) # number=14\n prog.x(input_qubit[2]) # number=15\n prog.x(input_qubit[3]) # number=16\n\n\n prog.h(input_qubit[0]) # number=17\n prog.h(input_qubit[1]) # number=18\n prog.cx(input_qubit[4],input_qubit[3]) # number=54\n prog.h(input_qubit[2]) # number=19\n prog.h(input_qubit[3]) # number=20\n\n\n prog.x(input_qubit[1]) # number=22\n prog.y(input_qubit[1]) # number=32\n prog.x(input_qubit[1]) # number=23\n prog.cx(input_qubit[4],input_qubit[3]) # number=55\n # circuit end\n\n for i in range(n):\n prog.measure(input_qubit[i], classical[i])\n\n\n return prog\n\n\n\n\nif __name__ == '__main__':\n key = \"00000\"\n f = lambda rep: str(int(rep == key))\n prog = make_circuit(5,f)\n backend = FakeVigo()\n sample_shot =7924\n\n info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()\n backend = FakeVigo()\n circuit1 = transpile(prog,backend,optimization_level=2)\n\n writefile = open(\"../data/startQiskit_noisy1857.csv\",\"w\")\n print(info,file=writefile)\n print(\"results end\", file=writefile)\n print(circuit1.depth(),file=writefile)\n print(circuit1,file=writefile)\n writefile.close()\n" ]
[ [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr", "numpy.identity" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.amax", "numpy.arange", "numpy.cos", "numpy.sin", "numpy.meshgrid" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ], [ "numpy.binary_repr" ] ]
[ { "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [], "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": [] } ]
JoZimmer/ParOptBeam
[ "50d15d8d822a2718f2932807e06c4a7e02f866a3" ]
[ "test_scripts/test_element_and_compare_to_kratos.py" ]
[ "from source.element.cr_beam_element import CRBeamElement\n\nimport numpy as np\n\nnp.set_printoptions(suppress=False, precision=4, linewidth=100)\n\n\ndef test_crbeam_element_update_incremental():\n material_params = {'rho': 7850, 'e': 2069000000.0, 'nu': 0.29, 'zeta': 0.05, 'lx_i': 1.2, 'is_nonlinear': True}\n element_params = {'a': 0.0001, 'asy': 0.0, 'asz': 0.0, 'iy': 0.0001, 'iz': 0.0001, 'it': 0.0001}\n\n coords = np.array([[1.2, 0.0, 0.0], [0.0, 0.0, 0.0]])\n element = CRBeamElement(material_params, element_params, coords, 0, '3D')\n\n Kd_kratos = np.array([\n [66828.2, 0, 0, 0, 0, 0],\n [0, 172417, 0, 0, 0, 0],\n [0, 0, 172417, 0, 0, 0],\n [0, 0, 0, 172417, 0, 0],\n [0, 0, 0, 0, 517250, 0],\n [0, 0, 0, 0, 0, 517250]\n ])\n\n Kd = element.Kd_mat\n\n try:\n assert (abs(Kd_kratos - Kd) < 10).all()\n except AssertionError:\n msg = \"##################################################################################\\n\"\n msg += \"Deformation Stiffness matrix\\n\"\n msg += \"Kd in Kratos:\\n\" + str(Kd_kratos)\n msg += \"\\nIt is however:\\n\" + str(Kd)\n print(msg)\n\n Ke_mat_kratos = np.array([\n [172417, 0, 0, 0, 0, 0, -172417, 0, 0, 0, 0, 0],\n [0, 1.43681e+06, 0, 0, 0, 862083, 0, -1.43681e+06, 0, 0, 0, 862083],\n [0, 0, 1.43681e+06, 0, -862083, 0, 0, 0, -1.43681e+06, 0, -862083, 0],\n [0, 0, 0, 66828.2, 0, 0, 0, 0, 0, -66828.2, 0, 0],\n [0, 0, -862083, 0, 689667, 0, 0, 0, 862083, 0, 344833, 0],\n [0, 862083, 0, 0, 0, 689667, 0, -862083, 0, 0, 0, 344833],\n [-172417, 0, 0, 0, 0, 0, 172417, 0, 0, 0, 0, 0],\n [0, -1.43681e+06, 0, 0, 0, -862083, 0, 1.43681e+06, 0, 0, 0, -862083],\n [0, 0, -1.43681e+06, 0, 862083, 0, 0, 0, 1.43681e+06, 0, 862083, 0],\n [0, 0, 0, -66828.2, 0, 0, 0, 0, 0, 66828.2, 0, 0],\n [0, 0, -862083, 0, 344833, 0, 0, 0, 862083, 0, 689667, 0],\n [0, 862083, 0, 0, 0, 344833, 0, -862083, 0, 0, 0, 689667]\n ])\n\n Ke_mat = element.Ke_mat\n\n try:\n assert (abs(Ke_mat_kratos - Ke_mat) < 10).all()\n except AssertionError:\n msg = \"##################################################################################\\n\"\n msg += \"Material Stiffness matrix\\n\"\n msg += \"Ke_mat in Kratos:\\n\" + str(Ke_mat_kratos)\n msg += \"\\nIt is however:\\n\" + str(Ke_mat)\n print(msg)\n\n Phiz = 0.0\n Phiy = 0.0\n\n CTy = (element.rho * element.A * element.L) / ((1 + Phiy) * (1 + Phiy))\n CTz = (element.rho * element.A * element.L) / ((1 + Phiz) * (1 + Phiz))\n\n CRy = (element.rho * element.Iy) / ((1 + Phiy) * (1 + Phiy) * element.L)\n CRz = (element.rho * element.Iz) / ((1 + Phiz) * (1 + Phiz) * element.L)\n\n bending_mass_matrix_z = element.build_single_mass_matrix(Phiz, CTz, CRz, element.L, +1)\n\n bending_mass_matrix_kratos_z = np.array([\n [1.13489, 0.137711, -0.663886, 0.0435114],\n [0.137711, 0.138519, -0.0435114, -0.0410891],\n [-0.663886, -0.0435114, 1.13489, -0.137711],\n [0.0435114, -0.0410891, -0.137711, 0.138519]\n ])\n\n try:\n assert (abs(bending_mass_matrix_z - bending_mass_matrix_kratos_z) < 1e-4).all()\n print(\"Bending mass_matrix z is correct\")\n except AssertionError:\n msg = \"##################################################################################\\n\"\n msg += \"Bending mass matrix z\\n\"\n msg += \"Me in Kratos:\\n\" + str(bending_mass_matrix_kratos_z)\n msg += \"\\nIt is however:\\n\" + str(bending_mass_matrix_z)\n print(msg)\n\n bending_mass_matrix_y = element.build_single_mass_matrix(Phiz, CTy, CRy, element.L, -1)\n\n bending_mass_matrix_kratos_y = np.array([\n [1.13489, -0.137711, -0.663886, -0.0435114],\n [-0.137711, 0.138519, 0.0435114, -0.0410891],\n [-0.663886, 0.0435114, 1.13489, 0.137711],\n [-0.0435114, -0.0410891, 0.137711, 0.138519]\n ])\n\n try:\n assert (abs(bending_mass_matrix_y - bending_mass_matrix_kratos_y) < 1e-4).all()\n print(\"Bending mass_matrix y is correct\")\n except AssertionError:\n msg = \"##################################################################################\\n\"\n msg += \"Bending mass matrix y\\n\"\n msg += \"Me in Kratos:\\n\" + str(bending_mass_matrix_kratos_y)\n msg += \"\\nIt is however:\\n\" + str(bending_mass_matrix_y)\n print(msg)\n\n Me = element._get_consistent_mass_matrix()\n\n Me_kratos = np.array([\n [0.314, 0, 0, 0, 0, 0, 0.157, 0, 0, 0, 0, 0],\n [0, 1.13489, 0, 0, 0, 0.137711, 0, -0.663886, 0, 0, 0, 0.0435114],\n [0, 0, 1.13489, 0, -0.137711, 0, 0, 0, -0.663886, 0, -0.0435114, 0],\n [0, 0, 0, 0.628, 0, 0, 0, 0, 0, 0.314, 0, 0],\n [0, 0, -0.137711, 0, 0.138519, 0, 0, 0, 0.0435114, 0, -0.0410891, 0],\n [0, 0.137711, 0, 0, 0, 0.138519, 0, -0.0435114, 0, 0, 0, -0.0410891],\n [0.157, 0, 0, 0, 0, 0, 0.314, 0, 0, 0, 0, 0],\n [0, -0.663886, 0, 0, 0, -0.0435114, 0, 1.13489, 0, 0, 0, -0.137711],\n [0, 0, -0.663886, 0, 0.0435114, 0, 0, 0, 1.13489, 0, 0.137711, 0],\n [0, 0, 0, 0.314, 0, 0, 0, 0, 0, 0.628, 0, 0],\n [0, 0, -0.0435114, 0, -0.0410891, 0, 0, 0, 0.137711, 0, 0.138519, 0],\n [0, 0.0435114, 0, 0, 0, -0.0410891, 0, -0.137711, 0, 0, 0, 0.138519]\n ])\n\n try:\n assert (abs(Me - Me_kratos) < 1e-2).all()\n print(\"Mass matrix is correct\")\n except AssertionError:\n msg = \"##################################################################################\\n\"\n msg += \"Consistent mass matrix\\n\"\n msg += \"Me in Kratos:\\n\" + str(Me_kratos)\n msg += \"\\nIt is however:\\n\" + str(Me)\n print(msg)\n" ]
[ [ "numpy.set_printoptions", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jab0707/UncertainSCI
[ "569c978c4f67dd7bb37e730276f2a376b8639235" ]
[ "tests/test_laguerre_inv.py" ]
[ "import unittest\n\nimport numpy as np\n\nfrom UncertainSCI.families import LaguerrePolynomials\n\n\nclass IDistTestCase(unittest.TestCase):\n \"\"\"\n Tests for (Laguerre polynomial) inversed induced distributions.\n \"\"\"\n\n def test_idistinv_laguerre(self):\n \"\"\"Evaluation of Laguerre inversed induced distribution function.\"\"\"\n\n # Randomly generate x, use idist to generate u\n rho = 11*np.random.random() - 1\n L = LaguerrePolynomials(rho=rho)\n\n n = int(np.ceil(10*np.random.rand(1))[0])\n M = 25\n x1 = 4*(n+1)*np.random.rand(M)\n u = L.idist(x1, n)\n\n # see if idistinv givens x back\n x2 = L.idistinv(u, n)\n\n delta = 5e-3\n ind = np.where(np.abs(x1-x2) > delta)[:2][0]\n if ind.size > 0:\n errstr = 'Failed for rho={0:1.3f}, n={1:d}'.format(rho, n)\n else:\n errstr = ''\n\n self.assertAlmostEqual(np.linalg.norm(x1-x2, ord=np.inf), 0., delta=delta, msg=errstr)\n\n\nif __name__ == \"__main__\":\n\n unittest.main(verbosity=2)\n" ]
[ [ "numpy.abs", "numpy.random.random", "numpy.linalg.norm", "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alnah005/aggregation-for-caesar
[ "d6bca0a1126e0397315d5773401c71075c33ee2f" ]
[ "panoptes_aggregation/running_reducers/tess_user_reducer.py" ]
[ "'''\nTESS User Reducer\n-----------------\nThis module porvides functions to calculate uesr weights for the TESS project.\nExtracts are from Ceasars `PluckFieldExtractor`.\n'''\nfrom .running_reducer_wrapper import running_reducer_wrapper\nimport numpy as np\n\n\n@running_reducer_wrapper(relevant_reduction=True)\ndef tess_user_reducer(data, **kwargs):\n '''Calculate TESS user weights\n\n Parameters\n ----------\n data : list\n A list with one item containing the extract with the user's feedback on a\n gold standard subject\n store : keyword, dict\n A dictinary with two keys:\n\n * `seed`: sum of all previous `seed` values\n * `count`: sum of all previous gold standard transits seen\n relevant_reduction : keyword, list\n A list with one item containing the results of the current subject's stats reducer.\n This item is a dictinary with two keys:\n\n * `True`: number of users who correctly identified the gold standard transits in the subject\n * `False`: number of users who incorrectly identified the gold standard transits in the subject\n\n Returns\n -------\n reduction : dict\n A dictinary with two keys:\n\n * `data`: A dictionary with the `skill` value as the only item\n * `store`: The updated store for the user\n '''\n success = [d['success'] for d in data[0]['feedback']]\n store = kwargs.pop('store')\n relevant_reduction = kwargs.pop('relevant_reduction')[0]\n try:\n d_subject = relevant_reduction['data']['difficulty']\n except:\n d_subject = 0\n\n seed_current = (np.where(success, 2, -1) * d_subject).sum()\n seed = store.get('seed', 0) + seed_current\n count = store.get('count', 0) + len(success)\n store = {\n 'seed': seed,\n 'count': count\n }\n c0 = 1\n skill = c0 * pow((1.0 + np.log10(count)), (seed / count))\n skill = min([3.0, max([0.05, skill])])\n return {\n 'skill': skill,\n '_store': store\n }\n" ]
[ [ "numpy.log10", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
StarGazer1995/OpenPCDet
[ "4af33e8badb0c8e68c7c94c71b0ec5667aad2348" ]
[ "pcdet/models/backbones_3d/spconv_unet.py" ]
[ "import torch\nimport torch.nn as nn\nimport spconv\nfrom functools import partial\nfrom .spconv_backbone import post_act_block\nfrom ...utils import common_utils\n\n\nclass SparseBasicBlock(spconv.SparseModule):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, indice_key=None, norm_fn=None):\n super(SparseBasicBlock, self).__init__()\n self.conv1 = spconv.SubMConv3d(\n inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False, indice_key=indice_key\n )\n self.bn1 = norm_fn(planes)\n self.relu = nn.ReLU()\n self.conv2 = spconv.SubMConv3d(\n planes, planes, kernel_size=3, stride=1, padding=1, bias=False, indice_key=indice_key\n )\n self.bn2 = norm_fn(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x.features\n\n assert x.features.dim() == 2, 'x.features.dim()=%d' % x.features.dim()\n\n out = self.conv1(x)\n out.features = self.bn1(out.features)\n out.features = self.relu(out.features)\n\n out = self.conv2(out)\n out.features = self.bn2(out.features)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out.features += identity\n out.features = self.relu(out.features)\n\n return out\n\n\nclass UNetV2(nn.Module):\n \"\"\"\n Sparse Convolution based UNet for point-wise feature learning.\n Reference Paper: https://arxiv.org/abs/1907.03670 (Shaoshuai Shi, et. al)\n From Points to Parts: 3D Object Detection from Point Cloud with Part-aware and Part-aggregation Network\n \"\"\"\n def __init__(self, model_cfg, input_channels, grid_size, voxel_size, point_cloud_range, **kwargs):\n super().__init__()\n self.model_cfg = model_cfg\n self.sparse_shape = grid_size[::-1] + [1, 0, 0]\n self.voxel_size = voxel_size\n self.point_cloud_range = point_cloud_range\n\n norm_fn = partial(nn.BatchNorm1d, eps=1e-3, momentum=0.01)\n\n self.conv_input = spconv.SparseSequential(\n spconv.SubMConv3d(input_channels, 16, 3, padding=1, bias=False, indice_key='subm1'),\n norm_fn(16),\n nn.ReLU(),\n )\n block = post_act_block\n\n self.conv1 = spconv.SparseSequential(\n block(16, 16, 3, norm_fn=norm_fn, padding=1, indice_key='subm1'),\n )\n\n self.conv2 = spconv.SparseSequential(\n # [1600, 1408, 41] <- [800, 704, 21]\n block(16, 32, 3, norm_fn=norm_fn, stride=2, padding=1, indice_key='spconv2', conv_type='spconv'),\n block(32, 32, 3, norm_fn=norm_fn, padding=1, indice_key='subm2'),\n block(32, 32, 3, norm_fn=norm_fn, padding=1, indice_key='subm2'),\n )\n\n self.conv3 = spconv.SparseSequential(\n # [800, 704, 21] <- [400, 352, 11]\n block(32, 64, 3, norm_fn=norm_fn, stride=2, padding=1, indice_key='spconv3', conv_type='spconv'),\n block(64, 64, 3, norm_fn=norm_fn, padding=1, indice_key='subm3'),\n block(64, 64, 3, norm_fn=norm_fn, padding=1, indice_key='subm3'),\n )\n\n self.conv4 = spconv.SparseSequential(\n # [400, 352, 11] <- [200, 176, 5]\n block(64, 64, 3, norm_fn=norm_fn, stride=2, padding=(0, 1, 1), indice_key='spconv4', conv_type='spconv'),\n block(64, 64, 3, norm_fn=norm_fn, padding=1, indice_key='subm4'),\n block(64, 64, 3, norm_fn=norm_fn, padding=1, indice_key='subm4'),\n )\n\n last_pad = 0\n last_pad = self.model_cfg.get('last_pad', last_pad)\n\n self.conv_out = spconv.SparseSequential(\n # [200, 150, 5] -> [200, 150, 2]\n spconv.SparseConv3d(64, 128, (3, 1, 1), stride=(2, 1, 1), padding=last_pad,\n bias=False, indice_key='spconv_down2'),\n norm_fn(128),\n nn.ReLU(),\n )\n\n # decoder\n # [400, 352, 11] <- [200, 176, 5]\n self.conv_up_t4 = SparseBasicBlock(64, 64, indice_key='subm4', norm_fn=norm_fn)\n self.conv_up_m4 = block(128, 64, 3, norm_fn=norm_fn, padding=1, indice_key='subm4')\n self.inv_conv4 = block(64, 64, 3, norm_fn=norm_fn, indice_key='spconv4', conv_type='inverseconv')\n\n # [800, 704, 21] <- [400, 352, 11]\n self.conv_up_t3 = SparseBasicBlock(64, 64, indice_key='subm3', norm_fn=norm_fn)\n self.conv_up_m3 = block(128, 64, 3, norm_fn=norm_fn, padding=1, indice_key='subm3')\n self.inv_conv3 = block(64, 32, 3, norm_fn=norm_fn, indice_key='spconv3', conv_type='inverseconv')\n\n # [1600, 1408, 41] <- [800, 704, 21]\n self.conv_up_t2 = SparseBasicBlock(32, 32, indice_key='subm2', norm_fn=norm_fn)\n self.conv_up_m2 = block(64, 32, 3, norm_fn=norm_fn, indice_key='subm2')\n self.inv_conv2 = block(32, 16, 3, norm_fn=norm_fn, indice_key='spconv2', conv_type='inverseconv')\n\n # [1600, 1408, 41] <- [1600, 1408, 41]\n self.conv_up_t1 = SparseBasicBlock(16, 16, indice_key='subm1', norm_fn=norm_fn)\n self.conv_up_m1 = block(32, 16, 3, norm_fn=norm_fn, indice_key='subm1')\n\n self.conv5 = spconv.SparseSequential(\n block(16, 16, 3, norm_fn=norm_fn, padding=1, indice_key='subm1')\n )\n self.num_point_features = 16\n\n def UR_block_forward(self, x_lateral, x_bottom, conv_t, conv_m, conv_inv):\n x_trans = conv_t(x_lateral)\n x = x_trans\n x.features = torch.cat((x_bottom.features, x_trans.features), dim=1)\n x_m = conv_m(x)\n x = self.channel_reduction(x, x_m.features.shape[1])\n x.features = x_m.features + x.features\n x = conv_inv(x)\n return x\n\n @staticmethod\n def channel_reduction(x, out_channels):\n \"\"\"\n Args:\n x: x.features (N, C1)\n out_channels: C2\n\n Returns:\n\n \"\"\"\n features = x.features\n n, in_channels = features.shape\n assert (in_channels % out_channels == 0) and (in_channels >= out_channels)\n\n x.features = features.view(n, out_channels, -1).sum(dim=2)\n return x\n\n def forward(self, batch_dict):\n \"\"\"\n Args:\n batch_dict:\n batch_size: int\n vfe_features: (num_voxels, C)\n voxel_coords: (num_voxels, 4), [batch_idx, z_idx, y_idx, x_idx]\n Returns:\n batch_dict:\n encoded_spconv_tensor: sparse tensor\n point_features: (N, C)\n \"\"\"\n voxel_features, voxel_coords = batch_dict['voxel_features'], batch_dict['voxel_coords']\n batch_size = batch_dict['batch_size']\n input_sp_tensor = spconv.SparseConvTensor(\n features=voxel_features,\n indices=voxel_coords.int(),\n spatial_shape=self.sparse_shape,\n batch_size=batch_size\n )\n x = self.conv_input(input_sp_tensor)\n \n x_conv1 = self.conv1(x)\n x_conv2 = self.conv2(x_conv1)\n x_conv3 = self.conv3(x_conv2)\n x_conv4 = self.conv4(x_conv3)\n\n # for detection head\n # [200, 176, 5] -> [200, 176, 2]\n out = self.conv_out(x_conv4)\n\n # for segmentation head\n # [400, 352, 11] <- [200, 176, 5]\n x_up4 = self.UR_block_forward(x_conv4, x_conv4, self.conv_up_t4, self.conv_up_m4, self.inv_conv4)\n # [800, 704, 21] <- [400, 352, 11]\n x_up3 = self.UR_block_forward(x_conv3, x_up4, self.conv_up_t3, self.conv_up_m3, self.inv_conv3)\n # [1600, 1408, 41] <- [800, 704, 21]\n x_up2 = self.UR_block_forward(x_conv2, x_up3, self.conv_up_t2, self.conv_up_m2, self.inv_conv2)\n # [1600, 1408, 41] <- [1600, 1408, 41]\n x_up1 = self.UR_block_forward(x_conv1, x_up2, self.conv_up_t1, self.conv_up_m1, self.conv5)\n\n batch_dict['point_features'] = x_up1.features\n point_coords = common_utils.get_voxel_centers(\n x_up1.indices[:, 1:], downsample_times=1, voxel_size=self.voxel_size,\n point_cloud_range=self.point_cloud_range\n )\n batch_dict['point_coords'] = torch.cat((x_up1.indices[:, 0:1].float(), point_coords), dim=1)\n batch_dict['encoded_spconv_tensor'] = out\n batch_dict['encoded_spconv_tensor_stride'] = 8\n return batch_dict\n" ]
[ [ "torch.nn.ReLU", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ChenLi0830/Clevo-Categorization-Service
[ "44b509786849a6dce610171d86e5da68ad748b4b" ]
[ "temp/train_cnn.py" ]
[ "'''This example demonstrates the use of Convolution1D for text classification.\n'''\n\nfrom __future__ import print_function\n\n\nimport sys\nsys.path.append('/Users/wangwei/anaconda2/envs/python3_keras/lib/python3.6/site-packages')\n\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers import Embedding\nfrom keras.layers import Conv1D, GlobalMaxPooling1D\nfrom keras import backend as K\n#os.chdir('/Users/wangwei/cuda_keras_projets/keras/examples/')\n\nimport six.moves.cPickle as pickle # for python 3\n#import cPickle for python 2.7\n\nimport pandas as pd\nimport numpy as np\n\nimport jieba\n\n\n# set parameters:\n\nmaxlen = 64 #11\nbatch_size = 5\nembedding_dims = 300\nfilters = 50 # 100\nkernel_size = 3\nhidden_dims = 100\nepochs = 10\n\ndef get_idx_from_sent(sent, word_idx_map, k=300):\n \"\"\"\n Transforms sentence into a list of indices. \n \"\"\"\n x = []\n words = list(jieba.cut(sent, cut_all=False)) \n\n \n for word in words:\n \n if word in word_idx_map:\n x.append(word_idx_map[word])\n return x\n\ndef make_idx_data_cv(revs, word_idx_map, cv, k=300):\n \"\"\"\n Transforms sentences into a 2-d matrix.\n \"\"\"\n train, test = [], []\n train_y, test_y = [],[]\n for rev in revs:\n sent = get_idx_from_sent(rev['text'], word_idx_map, k)\n \n if rev[\"split\"]==cv:\n test.append(sent)\n test_y.append(rev[\"y\"])\n else:\n train.append(sent)\n train_y.append(rev[\"y\"])\n #train = np.array(train, dtype='int')\n #test = np.array(test, dtype='int')\n \n return [train, test, train_y, test_y]\n\n\n\nif __name__==\"__main__\": \n print('The script that is running is :', __file__)\n print('Depending on the training datasets: \\n maximum length of a sentence is :', maxlen)\n\n\t######### Main code starts here ###########\n print(\"loading data...\")\n x = pickle.load(open(\"mr_folder/mr.p\",\"rb\"), encoding='latin1')\n revs, W, W2, word_idx_map, word_idx_map2, vocab = x[0], x[1], x[2], x[3], x[4],x[5]\n print(\"data loaded!\")\n print(\"using: word2vec vectors\")\n\n tmp = pd.DataFrame(revs)\n\n max_l = np.max(tmp[\"num_words\"])\n print(\"number of sentences: \" , str(len(revs)))\n print(\"vocab size: \" , str(len(vocab)))\n print(\"max sentence length: \" + str(max_l))\n\n max_features = len(vocab)#50\n\n #### Make datasets\n datasets = make_idx_data_cv(revs, word_idx_map2, 1, k=300)\n x_train = datasets[0]\n x_test = datasets[1]\n y_train = datasets[2]\n y_test = datasets[3]\n \n\n print('Pad sequences (samples x time)')\n x_train = sequence.pad_sequences(x_train, maxlen=maxlen)\n x_test = sequence.pad_sequences(x_test, maxlen=maxlen)\n print('x_train shape:', x_train.shape)\n print('x_test shape:', x_test.shape)\n\n ############# modelling with CNN\n import keras\n num_classes = 9\n # convert class vectors to binary class matrices\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, num_classes)\n print('lengh of y_train is :', y_train.shape[0])\n print('Build model...')\n\n K.clear_session()\n \n \n model = Sequential()\n \n # we start off with an efficient embedding layer which maps\n # our vocab indices into embedding_dims dimensions\n model.add(Embedding(max_features+1,\n\t embedding_dims,\n\t weights=[W],\n\t input_length=maxlen,\n\t trainable=False))\n model.add(Dropout(0.2))\n\n # we add a Convolution1D, which will learn filters\n # word group filters of size filter_length:\n model.add(Conv1D(filters,\n\t kernel_size,\n\t padding='valid',\n\t activation='relu',\n\t strides=1))\n # we use max pooling:\n model.add(GlobalMaxPooling1D())\n\n # We add a vanilla hidden layer:\n model.add(Dense(hidden_dims))\n model.add(Dropout(0.2))\n #model.add(Activation('relu'))\n\n # We project onto a single unit output layer, and squash it with a sigmoid:\n #model.add(Dense(1))\n model.add(Activation('sigmoid'))\n\n\n ######################\n model.add(Dropout(0.2))\n model.add(Dense(num_classes, activation='softmax'))\n # model.compile(loss=keras.losses.categorical_crossentropy,\n # optimizer=keras.optimizers.Adadelta(),\n # metrics=['accuracy'])\n model.compile(optimizer='rmsprop', \n\t loss='categorical_crossentropy', \n\t metrics=['accuracy'])\n model.fit(x_train, y_train,\n\t batch_size=batch_size,\n\t epochs=epochs,\n\t verbose=1,\n\t validation_data=(x_test, y_test))\n score = model.evaluate(x_test, y_test, verbose=0)\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])\n\n # serialize model to JSON\n model_json = model.to_json()\n with open(\"mr_folder/model.json\", \"w\") as json_file:\n json_file.write(model_json)\n # serialize weights to HDF5\n model.save_weights(\"mr_folder/model.h5\")\n print(\"Saved model to disk\")" ]
[ [ "numpy.max", "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": [] } ]
MOONJOOYOUNG/AdamP
[ "64a63106a2ac62bcbe90627f2a83ec1b488f3416" ]
[ "adamp/sgdp.py" ]
[ "\"\"\"\nAdamP\nCopyright (c) 2020-present NAVER Corp.\nMIT license\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim.optimizer import Optimizer, required\nimport math\n\nclass SGDP(Optimizer):\n def __init__(self, params, lr=required, momentum=0, dampening=0,\n weight_decay=0, nesterov=False, eps=1e-8, delta=0.1, wd_ratio=0.1):\n defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay,\n nesterov=nesterov, eps=eps, delta=delta, wd_ratio=wd_ratio)\n super(SGDP, self).__init__(params, defaults)\n\n def _channel_view(self, x):\n return x.view(x.size(0), -1)\n\n def _layer_view(self, x):\n return x.view(1, -1)\n\n def _cosine_similarity(self, x, y, eps, view_func):\n x = view_func(x)\n y = view_func(y)\n\n x_norm = x.norm(dim=1).add_(eps)\n y_norm = y.norm(dim=1).add_(eps)\n dot = (x * y).sum(dim=1)\n\n return dot.abs() / x_norm / y_norm\n\n def _projection(self, p, grad, perturb, delta, wd_ratio, eps):\n wd = 1\n expand_size = [-1] + [1] * (len(p.shape) - 1)\n for view_func in [self._channel_view, self._layer_view]:\n\n cosine_sim = self._cosine_similarity(grad, p.data, eps, view_func)\n\n if cosine_sim.max() < delta / math.sqrt(view_func(p.data).size(1)):\n p_n = p.data / view_func(p.data).norm(dim=1).view(expand_size).add_(eps)\n perturb -= p_n * view_func(p_n * perturb).sum(dim=1).view(expand_size)\n wd = wd_ratio\n\n return perturb, wd\n\n return perturb, wd\n\n def step(self, closure=None):\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n weight_decay = group['weight_decay']\n momentum = group['momentum']\n dampening = group['dampening']\n nesterov = group['nesterov']\n\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['momentum'] = torch.zeros_like(p.data)\n\n # SGD\n buf = state['momentum']\n buf.mul_(momentum).add_(1 - dampening, grad)\n if nesterov:\n d_p = grad + momentum * buf\n else:\n d_p = buf\n\n # Projection\n wd_ratio = 1\n if len(p.shape) > 1:\n d_p, wd_ratio = self._projection(p, grad, d_p, group['delta'], group['wd_ratio'], group['eps'])\n\n # Weight decay\n if weight_decay != 0:\n p.data.mul_(1 - group['lr'] * group['weight_decay'] * wd_ratio / (1-momentum))\n\n # Step\n p.data.add_(-group['lr'], d_p)\n\n return loss\n" ]
[ [ "torch.zeros_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
antgonza/qtp-diversity
[ "0c2ec84711decf798ea6ffdb3e97dc9582ba4035" ]
[ "qtp_diversity/tests/test_validate.py" ]
[ "# -----------------------------------------------------------------------------\n# Copyright (c) 2014--, The Qiita Development Team.\n#\n# Distributed under the terms of the BSD 3-clause License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# -----------------------------------------------------------------------------\n\nfrom unittest import main\nfrom tempfile import mkdtemp, mkstemp\nfrom os.path import exists, isdir, join\nfrom os import remove, close\nfrom shutil import rmtree\nfrom json import dumps\n\nfrom skbio.stats.distance import randdm\nfrom skbio import OrdinationResults\nfrom qiita_client import ArtifactInfo\nfrom qiita_client.testing import PluginTestCase\nimport pandas as pd\nimport numpy as np\n\nfrom qtp_diversity import plugin\nfrom qtp_diversity.validate import (\n _validate_distance_matrix, _validate_ordination_results,\n _validate_alpha_vector, _validate_feature_data_taxonomy, validate)\n\n\nclass ValidateTests(PluginTestCase):\n def setUp(self):\n self.out_dir = mkdtemp()\n self._clean_up_files = [self.out_dir]\n self.metadata = {\n '1.SKM4.640180': {'col': \"doesn't really matters\"},\n '1.SKB8.640193': {'col': \"doesn't really matters\"},\n '1.SKD8.640184': {'col': \"doesn't really matters\"},\n '1.SKM9.640192': {'col': \"doesn't really matters\"},\n '1.SKB7.640196': {'col': \"doesn't really matters\"}}\n\n plugin('https://localhost:8383', 'register', 'ignored')\n\n def tearDown(self):\n for fp in self._clean_up_files:\n if exists(fp):\n if isdir(fp):\n rmtree(fp)\n else:\n remove(fp)\n\n def _create_distance_matrix(self, sample_ids):\n dm = randdm(len(sample_ids), sample_ids)\n fd, fp = mkstemp(suffix='.txt', dir=self.out_dir)\n close(fd)\n dm.write(fp)\n return fp\n\n def _create_ordination_results(self, sample_ids):\n eigvals = [0.51236726, 0.30071909, 0.26791207, 0.20898868]\n proportion_explained = [0.2675738328, 0.157044696, 0.1399118638,\n 0.1091402725]\n axis_labels = ['PC1', 'PC2', 'PC3', 'PC4']\n samples = [[-2.584, 1.739, 3.828, -1.944],\n [-2.710, -1.859, -8.648, 1.180],\n [2.350, 9.625, -3.457, -3.208],\n [2.614, -1.114, 1.476, 2.908],\n [2.850, -1.925, 6.232, 1.381]]\n ord_res = OrdinationResults(\n short_method_name='PCoA',\n long_method_name='Principal Coordinate Analysis',\n eigvals=pd.Series(eigvals, index=axis_labels),\n samples=pd.DataFrame(np.asarray(samples), index=sample_ids,\n columns=axis_labels),\n proportion_explained=pd.Series(proportion_explained,\n index=axis_labels))\n fd, fp = mkstemp(suffix='.txt', dir=self.out_dir)\n close(fd)\n ord_res.write(fp)\n return fp\n\n def _create_alpha_vector(self, sample_ids):\n fd, fp = mkstemp(suffix='.txt', dir=self.out_dir)\n close(fd)\n with open(fp, 'w') as f:\n f.write(\"\\tobserved_otus\\n\")\n for s_id in sample_ids:\n f.write(\"%s\\t%d\\n\" % (s_id, np.random.randint(1, 200)))\n\n return fp\n\n def _create_job(self, a_type, files, analysis):\n parameters = {'template': None,\n 'files': dumps(files),\n 'artifact_type': a_type,\n 'analysis': analysis}\n data = {'command': dumps(['Diversity types', '0.1.1', 'Validate']),\n 'parameters': dumps(parameters),\n 'status': 'running'}\n job_id = self.qclient.post(\n '/apitest/processing_job/', data=data)['job']\n return job_id, parameters\n\n def test_validate_distance_matrix(self):\n # Create a distance matrix\n sample_ids = ['1.SKM4.640180', '1.SKB8.640193', '1.SKD8.640184',\n '1.SKM9.640192', '1.SKB7.640196']\n dm_fp = self._create_distance_matrix(sample_ids)\n\n # Test success\n obs_success, obs_ainfo, obs_error = _validate_distance_matrix(\n {'plain_text': [dm_fp]}, self.metadata, self.out_dir)\n self.assertTrue(obs_success)\n exp_ainfo = [ArtifactInfo(None, \"distance_matrix\",\n [(dm_fp, 'plain_text')])]\n self.assertEqual(obs_ainfo, exp_ainfo)\n self.assertEqual(obs_error, \"\")\n\n # Test failure\n sample_ids = ['1.SKM4.640180', '1.SKB8.640193', '1.SKD8.640184',\n '1.SKM9.640192', 'NotASample']\n dm_fp = self._create_distance_matrix(sample_ids)\n obs_success, obs_ainfo, obs_error = _validate_distance_matrix(\n {'plain_text': [dm_fp]}, self.metadata, self.out_dir)\n self.assertFalse(obs_success)\n self.assertIsNone(obs_ainfo)\n self.assertEqual(obs_error, \"The distance matrix contain samples not \"\n \"present in the metadata\")\n\n def test_validate_ordination_results(self):\n # Create the ordination results\n sample_ids = ['1.SKM4.640180', '1.SKB8.640193', '1.SKD8.640184',\n '1.SKM9.640192', '1.SKB7.640196']\n ord_res_fp = self._create_ordination_results(sample_ids)\n\n # Test success\n obs_success, obs_ainfo, obs_error = _validate_ordination_results(\n {'plain_text': [ord_res_fp]}, self.metadata, self.out_dir)\n self.assertTrue(obs_success)\n exp_ainfo = [ArtifactInfo(None, \"ordination_results\",\n [(ord_res_fp, 'plain_text')])]\n self.assertEqual(obs_ainfo, exp_ainfo)\n self.assertEqual(obs_error, \"\")\n\n # Test failure\n sample_ids = ['1.SKM4.640180', '1.SKB8.640193', '1.SKD8.640184',\n '1.SKM9.640192', 'NotASample']\n ord_res_fp = self._create_ordination_results(sample_ids)\n obs_success, obs_ainfo, obs_error = _validate_ordination_results(\n {'plain_text': [ord_res_fp]}, self.metadata, self.out_dir)\n self.assertFalse(obs_success)\n self.assertIsNone(obs_ainfo)\n self.assertEqual(obs_error, \"The ordination results contain samples \"\n \"not present in the metadata\")\n\n def test_validate_alpha_vector(self):\n # Create the alpha vector\n sample_ids = ['1.SKM4.640180', '1.SKB8.640193', '1.SKD8.640184',\n '1.SKM9.640192']\n alpha_vector_fp = self._create_alpha_vector(sample_ids)\n\n # Test success\n obs_success, obs_ainfo, obs_error = _validate_alpha_vector(\n {'plain_text': [alpha_vector_fp]}, self.metadata, self.out_dir)\n self.assertEqual(obs_error, \"\")\n self.assertTrue(obs_success)\n exp_ainfo = [ArtifactInfo(None, \"alpha_vector\",\n [(alpha_vector_fp, 'plain_text')])]\n self.assertEqual(obs_ainfo, exp_ainfo)\n\n # Test failure wrong ids\n sample_ids = ['1.SKM4.640180', '1.SKB8.640193', '1.SKD8.640184',\n 'NotASample']\n alpha_vector_fp = self._create_alpha_vector(sample_ids)\n obs_success, obs_ainfo, obs_error = _validate_alpha_vector(\n {'plain_text': [alpha_vector_fp]}, self.metadata, self.out_dir)\n self.assertEqual(obs_error, \"The alpha vector contains samples not \"\n \"present in the metadata\")\n self.assertFalse(obs_success)\n self.assertIsNone(obs_ainfo)\n\n # Test failure wrong format\n fd, alpha_vector_fp = mkstemp(suffix='.txt', dir=self.out_dir)\n close(fd)\n with open(alpha_vector_fp, 'w') as f:\n f.write(\"\\tobserved_otus\\nsample 1\\n\")\n obs_success, obs_ainfo, obs_error = _validate_alpha_vector(\n {'plain_text': [alpha_vector_fp]}, self.metadata, self.out_dir)\n self.assertEqual(obs_error, \"The alpha vector format is incorrect\")\n self.assertFalse(obs_success)\n self.assertIsNone(obs_ainfo)\n\n def test_validate(self):\n # Test artifact type error\n job_id, params = self._create_job(\n 'NotAType', {'plan_text': 'Will fail before checking this'}, 1)\n obs_success, obs_ainfo, obs_error = validate(\n self.qclient, job_id, params, self.out_dir)\n self.assertFalse(obs_success)\n self.assertIsNone(obs_ainfo)\n self.assertEqual(\n obs_error, \"Unknown artifact type NotAType. Supported types: \"\n \"FeatureData[Taxonomy], alpha_vector, distance_matrix, \"\n \"ordination_results\")\n\n # Test missing metadata error - to be fair, I don't know how this error\n # can happen in the live system, but better be safe than sorry\n job_id, params = self._create_job(\n 'distance_matrix', {'plan_text': 'Will fail before checking this'},\n None)\n obs_success, obs_ainfo, obs_error = validate(\n self.qclient, job_id, params, self.out_dir)\n self.assertFalse(obs_success)\n self.assertIsNone(obs_ainfo)\n self.assertEqual(\n obs_error, \"Missing metadata information\")\n\n # Test distance matrix success\n sample_ids = ['1.SKM4.640180', '1.SKB8.640193', '1.SKD8.640184',\n '1.SKM9.640192', '1.SKB7.640196']\n dm_fp = self._create_distance_matrix(sample_ids)\n job_id, params = self._create_job(\n 'distance_matrix', {'plain_text': [dm_fp]}, 1)\n obs_success, obs_ainfo, obs_error = validate(\n self.qclient, job_id, params, self.out_dir)\n self.assertTrue(obs_success)\n html_fp = join(self.out_dir, 'index.html')\n exp_ainfo = [ArtifactInfo(None, \"distance_matrix\",\n [(dm_fp, 'plain_text'),\n (html_fp, 'html_summary')])]\n self.assertEqual(obs_ainfo, exp_ainfo)\n self.assertEqual(obs_error, \"\")\n\n # Test ordination results success\n ord_res_fp = self._create_ordination_results(sample_ids)\n job_id, params = self._create_job(\n 'ordination_results', {'plain_text': [ord_res_fp]}, 1)\n obs_success, obs_ainfo, obs_error = validate(\n self.qclient, job_id, params, self.out_dir)\n self.assertTrue(obs_success)\n html_fp = join(self.out_dir, 'index.html')\n esf_fp = join(self.out_dir, 'emperor_support_files')\n exp_ainfo = [ArtifactInfo(None, \"ordination_results\",\n [(ord_res_fp, 'plain_text'),\n (html_fp, 'html_summary'),\n (esf_fp, 'html_summary_dir')])]\n self.assertEqual(obs_ainfo, exp_ainfo)\n self.assertEqual(obs_error, \"\")\n\n # Test alpha vector success\n alpha_vector_fp = self._create_alpha_vector(sample_ids)\n job_id, params = self._create_job(\n 'alpha_vector', {'plain_text': [alpha_vector_fp]}, 1)\n obs_success, obs_ainfo, obs_error = validate(\n self.qclient, job_id, params, self.out_dir)\n self.assertTrue(obs_success)\n html_fp = join(self.out_dir, 'index.html')\n sf_fp = join(self.out_dir, 'support_files')\n exp_ainfo = [ArtifactInfo(None, \"alpha_vector\",\n [(alpha_vector_fp, 'plain_text'),\n (html_fp, 'html_summary'),\n (sf_fp, 'html_summary_dir')])]\n self.assertEqual(obs_ainfo, exp_ainfo)\n self.assertEqual(obs_error, \"\")\n\n def test_validate_FeatureData_Taxonomy(self):\n # Create the feature data\n fd, taxonomy_fp = mkstemp(suffix='.txt', dir=self.out_dir)\n close(fd)\n with open(taxonomy_fp, 'w') as f:\n f.write(\"Feature ID\\tTaxonomy\\tConfidence\\n\")\n f.write(\"TACGGAGGA\\tk__Bacteria;p__Bacteroidetes;c__Bacteroidia\\t\"\n \"0.9998743\\n\")\n f.write(\"TACGTAGGG\\tk__Bacteria;p__Firmicutes;c__Clostridia\\t\"\n \"0.9999999\\n\")\n\n # Test success\n obs_success, obs_ainfo, obs_error = _validate_feature_data_taxonomy(\n {'plain_text': [taxonomy_fp]}, None, self.out_dir)\n self.assertEqual(obs_error, \"\")\n self.assertTrue(obs_success)\n exp_ainfo = [ArtifactInfo(None, \"FeatureData[Taxonomy]\",\n [(taxonomy_fp, 'plain_text')])]\n self.assertEqual(obs_ainfo, exp_ainfo)\n\n # Test failure wrong format\n fd, taxonomy_fp = mkstemp(suffix='.txt', dir=self.out_dir)\n close(fd)\n with open(taxonomy_fp, 'w') as f:\n f.write(\"Feature ID\\tIt's gonna fail!\\tConfidence\\n\")\n f.write(\"TACGGAGGA\\tk__Bacteria;p__Bacteroidetes;c__Bacteroidia\\t\"\n \"0.9998743\\n\")\n f.write(\"TACGTAGGG\\tk__Bacteria;p__Firmicutes;c__Clostridia\\t\"\n \"0.9999999\\n\")\n obs_success, obs_ainfo, obs_error = _validate_feature_data_taxonomy(\n {'plain_text': [taxonomy_fp]}, None, self.out_dir)\n self.assertIn(\"The file header seems wrong\", obs_error)\n self.assertFalse(obs_success)\n self.assertIsNone(obs_ainfo)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.asarray", "pandas.Series", "numpy.random.randint" ] ]
[ { "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": [] } ]
methane/astropy
[ "1a065d5ce403e226799cfb3d606fda33be0a6c08", "1a065d5ce403e226799cfb3d606fda33be0a6c08" ]
[ "astropy/coordinates/sky_coordinate.py", "astropy/io/fits/tests/test_core.py" ]
[ "import re\nimport copy\nimport warnings\nimport operator\n\nimport numpy as np\n\nfrom astropy import _erfa as erfa\nfrom astropy.utils.compat.misc import override__dir__\nfrom astropy import units as u\nfrom astropy.constants import c as speed_of_light\nfrom astropy.utils.data_info import MixinInfo\nfrom astropy.utils import ShapedLikeNDArray\nfrom astropy.time import Time\nfrom astropy.utils.exceptions import AstropyUserWarning\n\nfrom .distances import Distance\nfrom .angles import Angle\nfrom .baseframe import (BaseCoordinateFrame, frame_transform_graph,\n GenericFrame)\nfrom .builtin_frames import ICRS, SkyOffsetFrame\nfrom .representation import (SphericalRepresentation,\n UnitSphericalRepresentation, SphericalDifferential)\nfrom .sky_coordinate_parsers import (_get_frame_class, _get_frame_without_data,\n _parse_coordinate_data)\n\n__all__ = ['SkyCoord', 'SkyCoordInfo']\n\n\nclass SkyCoordInfo(MixinInfo):\n \"\"\"\n Container for meta information like name, description, format. This is\n required when the object is used as a mixin column within a table, but can\n be used as a general way to store meta information.\n \"\"\"\n attrs_from_parent = set(['unit']) # Unit is read-only\n _supports_indexing = False\n\n @staticmethod\n def default_format(val):\n repr_data = val.info._repr_data\n formats = ['{0.' + compname + '.value:}' for compname\n in repr_data.components]\n return ','.join(formats).format(repr_data)\n\n @property\n def unit(self):\n repr_data = self._repr_data\n unit = ','.join(str(getattr(repr_data, comp).unit) or 'None'\n for comp in repr_data.components)\n return unit\n\n @property\n def _repr_data(self):\n if self._parent is None:\n return None\n\n sc = self._parent\n if (issubclass(sc.representation_type, SphericalRepresentation)\n and isinstance(sc.data, UnitSphericalRepresentation)):\n repr_data = sc.represent_as(sc.data.__class__, in_frame_units=True)\n else:\n repr_data = sc.represent_as(sc.representation_type,\n in_frame_units=True)\n return repr_data\n\n def _represent_as_dict(self):\n obj = self._parent\n attrs = (list(obj.representation_component_names) +\n list(frame_transform_graph.frame_attributes.keys()))\n\n # Don't output distance if it is all unitless 1.0\n if 'distance' in attrs and np.all(obj.distance == 1.0):\n attrs.remove('distance')\n\n out = super()._represent_as_dict(attrs)\n\n out['representation_type'] = obj.representation_type.get_name()\n out['frame'] = obj.frame.name\n # Note that obj.info.unit is a fake composite unit (e.g. 'deg,deg,None'\n # or None,None,m) and is not stored. The individual attributes have\n # units.\n\n return out\n\n def new_like(self, skycoords, length, metadata_conflicts='warn', name=None):\n \"\"\"\n Return a new SkyCoord instance which is consistent with the input\n SkyCoord objects ``skycoords`` and has ``length`` rows. Being\n \"consistent\" is defined as being able to set an item from one to each of\n the rest without any exception being raised.\n\n This is intended for creating a new SkyCoord instance whose elements can\n be set in-place for table operations like join or vstack. This is used\n when a SkyCoord object is used as a mixin column in an astropy Table.\n\n The data values are not predictable and it is expected that the consumer\n of the object will fill in all values.\n\n Parameters\n ----------\n skycoords : list\n List of input SkyCoord objects\n length : int\n Length of the output skycoord object\n metadata_conflicts : str ('warn'|'error'|'silent')\n How to handle metadata conflicts\n name : str\n Output name (sets output skycoord.info.name)\n\n Returns\n -------\n skycoord : SkyCoord (or subclass)\n Instance of this class consistent with ``skycoords``\n\n \"\"\"\n # Get merged info attributes like shape, dtype, format, description, etc.\n attrs = self.merge_cols_attributes(skycoords, metadata_conflicts, name,\n ('meta', 'description'))\n skycoord0 = skycoords[0]\n\n # Make a new SkyCoord object with the desired length and attributes\n # by using the _apply / __getitem__ machinery to effectively return\n # skycoord0[[0, 0, ..., 0, 0]]. This will have the all the right frame\n # attributes with the right shape.\n indexes = np.zeros(length, dtype=np.int64)\n out = skycoord0[indexes]\n\n # Use __setitem__ machinery to check for consistency of all skycoords\n for skycoord in skycoords[1:]:\n try:\n out[0] = skycoord[0]\n except Exception as err:\n raise ValueError(f'input skycoords are inconsistent: {err}')\n\n # Set (merged) info attributes\n for attr in ('name', 'meta', 'description'):\n if attr in attrs:\n setattr(out.info, attr, attrs[attr])\n\n return out\n\n\nclass SkyCoord(ShapedLikeNDArray):\n \"\"\"High-level object providing a flexible interface for celestial coordinate\n representation, manipulation, and transformation between systems.\n\n The `SkyCoord` class accepts a wide variety of inputs for initialization. At\n a minimum these must provide one or more celestial coordinate values with\n unambiguous units. Inputs may be scalars or lists/tuples/arrays, yielding\n scalar or array coordinates (can be checked via ``SkyCoord.isscalar``).\n Typically one also specifies the coordinate frame, though this is not\n required. The general pattern for spherical representations is::\n\n SkyCoord(COORD, [FRAME], keyword_args ...)\n SkyCoord(LON, LAT, [FRAME], keyword_args ...)\n SkyCoord(LON, LAT, [DISTANCE], frame=FRAME, unit=UNIT, keyword_args ...)\n SkyCoord([FRAME], <lon_attr>=LON, <lat_attr>=LAT, keyword_args ...)\n\n It is also possible to input coordinate values in other representations\n such as cartesian or cylindrical. In this case one includes the keyword\n argument ``representation_type='cartesian'`` (for example) along with data\n in ``x``, ``y``, and ``z``.\n\n See also: http://docs.astropy.org/en/stable/coordinates/\n\n Examples\n --------\n The examples below illustrate common ways of initializing a `SkyCoord`\n object. For a complete description of the allowed syntax see the\n full coordinates documentation. First some imports::\n\n >>> from astropy.coordinates import SkyCoord # High-level coordinates\n >>> from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames\n >>> from astropy.coordinates import Angle, Latitude, Longitude # Angles\n >>> import astropy.units as u\n\n The coordinate values and frame specification can now be provided using\n positional and keyword arguments::\n\n >>> c = SkyCoord(10, 20, unit=\"deg\") # defaults to ICRS frame\n >>> c = SkyCoord([1, 2, 3], [-30, 45, 8], frame=\"icrs\", unit=\"deg\") # 3 coords\n\n >>> coords = [\"1:12:43.2 +31:12:43\", \"1 12 43.2 +31 12 43\"]\n >>> c = SkyCoord(coords, frame=FK4, unit=(u.hourangle, u.deg), obstime=\"J1992.21\")\n\n >>> c = SkyCoord(\"1h12m43.2s +1d12m43s\", frame=Galactic) # Units from string\n >>> c = SkyCoord(frame=\"galactic\", l=\"1h12m43.2s\", b=\"+1d12m43s\")\n\n >>> ra = Longitude([1, 2, 3], unit=u.deg) # Could also use Angle\n >>> dec = np.array([4.5, 5.2, 6.3]) * u.deg # Astropy Quantity\n >>> c = SkyCoord(ra, dec, frame='icrs')\n >>> c = SkyCoord(frame=ICRS, ra=ra, dec=dec, obstime='2001-01-02T12:34:56')\n\n >>> c = FK4(1 * u.deg, 2 * u.deg) # Uses defaults for obstime, equinox\n >>> c = SkyCoord(c, obstime='J2010.11', equinox='B1965') # Override defaults\n\n >>> c = SkyCoord(w=0, u=1, v=2, unit='kpc', frame='galactic',\n ... representation_type='cartesian')\n\n >>> c = SkyCoord([ICRS(ra=1*u.deg, dec=2*u.deg), ICRS(ra=3*u.deg, dec=4*u.deg)])\n\n Velocity components (proper motions or radial velocities) can also be\n provided in a similar manner::\n\n >>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, radial_velocity=10*u.km/u.s)\n\n >>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, pm_ra_cosdec=2*u.mas/u.yr, pm_dec=1*u.mas/u.yr)\n\n As shown, the frame can be a `~astropy.coordinates.BaseCoordinateFrame`\n class or the corresponding string alias. The frame classes that are built in\n to astropy are `ICRS`, `FK5`, `FK4`, `FK4NoETerms`, and `Galactic`.\n The string aliases are simply lower-case versions of the class name, and\n allow for creating a `SkyCoord` object and transforming frames without\n explicitly importing the frame classes.\n\n Parameters\n ----------\n frame : `~astropy.coordinates.BaseCoordinateFrame` class or string, optional\n Type of coordinate frame this `SkyCoord` should represent. Defaults to\n to ICRS if not given or given as None.\n unit : `~astropy.units.Unit`, string, or tuple of :class:`~astropy.units.Unit` or str, optional\n Units for supplied ``LON`` and ``LAT`` values, respectively. If\n only one unit is supplied then it applies to both ``LON`` and\n ``LAT``.\n obstime : valid `~astropy.time.Time` initializer, optional\n Time(s) of observation.\n equinox : valid `~astropy.time.Time` initializer, optional\n Coordinate frame equinox.\n representation_type : str or Representation class\n Specifies the representation, e.g. 'spherical', 'cartesian', or\n 'cylindrical'. This affects the positional args and other keyword args\n which must correspond to the given representation.\n copy : bool, optional\n If `True` (default), a copy of any coordinate data is made. This\n argument can only be passed in as a keyword argument.\n **keyword_args\n Other keyword arguments as applicable for user-defined coordinate frames.\n Common options include:\n\n ra, dec : valid `~astropy.coordinates.Angle` initializer, optional\n RA and Dec for frames where ``ra`` and ``dec`` are keys in the\n frame's ``representation_component_names``, including `ICRS`,\n `FK5`, `FK4`, and `FK4NoETerms`.\n pm_ra_cosdec, pm_dec : `~astropy.units.Quantity`, optional\n Proper motion components, in angle per time units.\n l, b : valid `~astropy.coordinates.Angle` initializer, optional\n Galactic ``l`` and ``b`` for for frames where ``l`` and ``b`` are\n keys in the frame's ``representation_component_names``, including\n the `Galactic` frame.\n pm_l_cosb, pm_b : `~astropy.units.Quantity`, optional\n Proper motion components in the `Galactic` frame, in angle per time\n units.\n x, y, z : float or `~astropy.units.Quantity`, optional\n Cartesian coordinates values\n u, v, w : float or `~astropy.units.Quantity`, optional\n Cartesian coordinates values for the Galactic frame.\n radial_velocity : `~astropy.units.Quantity`, optional\n The component of the velocity along the line-of-sight (i.e., the\n radial direction), in velocity units.\n \"\"\"\n\n # Declare that SkyCoord can be used as a Table column by defining the\n # info property.\n info = SkyCoordInfo()\n\n def __init__(self, *args, copy=True, **kwargs):\n\n # these are frame attributes set on this SkyCoord but *not* a part of\n # the frame object this SkyCoord contains\n self._extra_frameattr_names = set()\n\n # If all that is passed in is a frame instance that already has data,\n # we should bypass all of the parsing and logic below. This is here\n # to make this the fastest way to create a SkyCoord instance. Many of\n # the classmethods implemented for performance enhancements will use\n # this as the initialization path\n if (len(args) == 1 and len(kwargs) == 0\n and isinstance(args[0], (BaseCoordinateFrame, SkyCoord))):\n\n coords = args[0]\n if isinstance(coords, SkyCoord):\n self._extra_frameattr_names = coords._extra_frameattr_names\n self.info = coords.info\n\n # Copy over any extra frame attributes\n for attr_name in self._extra_frameattr_names:\n # Setting it will also validate it.\n setattr(self, attr_name, getattr(coords, attr_name))\n\n coords = coords.frame\n\n if not coords.has_data:\n raise ValueError('Cannot initialize from a coordinate frame '\n 'instance without coordinate data')\n\n if copy:\n self._sky_coord_frame = coords.copy()\n else:\n self._sky_coord_frame = coords\n\n else:\n # Get the frame instance without coordinate data but with all frame\n # attributes set - these could either have been passed in with the\n # frame as an instance, or passed in as kwargs here\n frame_cls, frame_kwargs = _get_frame_without_data(args, kwargs)\n\n # Parse the args and kwargs to assemble a sanitized and validated\n # kwargs dict for initializing attributes for this object and for\n # creating the internal self._sky_coord_frame object\n args = list(args) # Make it mutable\n skycoord_kwargs, components, info = _parse_coordinate_data(\n frame_cls(**frame_kwargs), args, kwargs)\n\n # In the above two parsing functions, these kwargs were identified\n # as valid frame attributes for *some* frame, but not the frame that\n # this SkyCoord will have. We keep these attributes as special\n # skycoord frame attributes:\n for attr in skycoord_kwargs:\n # Setting it will also validate it.\n setattr(self, attr, skycoord_kwargs[attr])\n\n if info is not None:\n self.info = info\n\n # Finally make the internal coordinate object.\n frame_kwargs.update(components)\n self._sky_coord_frame = frame_cls(copy=copy, **frame_kwargs)\n\n if not self._sky_coord_frame.has_data:\n raise ValueError('Cannot create a SkyCoord without data')\n\n @property\n def frame(self):\n return self._sky_coord_frame\n\n @property\n def representation_type(self):\n return self.frame.representation_type\n\n @representation_type.setter\n def representation_type(self, value):\n self.frame.representation_type = value\n\n # TODO: remove these in future\n @property\n def representation(self):\n return self.frame.representation\n\n @representation.setter\n def representation(self, value):\n self.frame.representation = value\n\n @property\n def shape(self):\n return self.frame.shape\n\n def __eq__(self, value):\n \"\"\"Equality operator for SkyCoord\n\n This implements strict equality and requires that the frames are\n equivalent, extra frame attributes are equivalent, and that the\n representation data are exactly equal.\n \"\"\"\n # Make sure that any extra frame attribute names are equivalent.\n for attr in self._extra_frameattr_names | value._extra_frameattr_names:\n if not self.frame._frameattr_equiv(getattr(self, attr),\n getattr(value, attr)):\n raise ValueError(f\"cannot compare: extra frame attribute \"\n f\"'{attr}' is not equivalent \"\n f\"(perhaps compare the frames directly to avoid \"\n f\"this exception)\")\n\n return self._sky_coord_frame == value._sky_coord_frame\n\n def __ne__(self, value):\n return np.logical_not(self == value)\n\n def _apply(self, method, *args, **kwargs):\n \"\"\"Create a new instance, applying a method to the underlying data.\n\n In typical usage, the method is any of the shape-changing methods for\n `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those\n picking particular elements (``__getitem__``, ``take``, etc.), which\n are all defined in `~astropy.utils.shapes.ShapedLikeNDArray`. It will be\n applied to the underlying arrays in the representation (e.g., ``x``,\n ``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`),\n as well as to any frame attributes that have a shape, with the results\n used to create a new instance.\n\n Internally, it is also used to apply functions to the above parts\n (in particular, `~numpy.broadcast_to`).\n\n Parameters\n ----------\n method : str or callable\n If str, it is the name of a method that is applied to the internal\n ``components``. If callable, the function is applied.\n args : tuple\n Any positional arguments for ``method``.\n kwargs : dict\n Any keyword arguments for ``method``.\n \"\"\"\n def apply_method(value):\n if isinstance(value, ShapedLikeNDArray):\n return value._apply(method, *args, **kwargs)\n else:\n if callable(method):\n return method(value, *args, **kwargs)\n else:\n return getattr(value, method)(*args, **kwargs)\n\n # create a new but empty instance, and copy over stuff\n new = super().__new__(self.__class__)\n new._sky_coord_frame = self._sky_coord_frame._apply(method,\n *args, **kwargs)\n new._extra_frameattr_names = self._extra_frameattr_names.copy()\n for attr in self._extra_frameattr_names:\n value = getattr(self, attr)\n if getattr(value, 'shape', ()):\n value = apply_method(value)\n elif method == 'copy' or method == 'flatten':\n # flatten should copy also for a single element array, but\n # we cannot use it directly for array scalars, since it\n # always returns a one-dimensional array. So, just copy.\n value = copy.copy(value)\n setattr(new, '_' + attr, value)\n\n # Copy other 'info' attr only if it has actually been defined.\n # See PR #3898 for further explanation and justification, along\n # with Quantity.__array_finalize__\n if 'info' in self.__dict__:\n new.info = self.info\n\n return new\n\n def __setitem__(self, item, value):\n \"\"\"Implement self[item] = value for SkyCoord\n\n The right hand ``value`` must be strictly consistent with self:\n - Identical class\n - Equivalent frames\n - Identical representation_types\n - Identical representation differentials keys\n - Identical frame attributes\n - Identical \"extra\" frame attributes (e.g. obstime for an ICRS coord)\n\n With these caveats the setitem ends up as effectively a setitem on\n the representation data.\n\n self.frame.data[item] = value.frame.data\n \"\"\"\n if self.__class__ is not value.__class__:\n raise TypeError(f'can only set from object of same class: '\n f'{self.__class__.__name__} vs. '\n f'{value.__class__.__name__}')\n\n # Make sure that any extra frame attribute names are equivalent.\n for attr in self._extra_frameattr_names | value._extra_frameattr_names:\n if not self.frame._frameattr_equiv(getattr(self, attr),\n getattr(value, attr)):\n raise ValueError(f'attribute {attr} is not equivalent')\n\n # Set the frame values. This checks frame equivalence and also clears\n # the cache to ensure that the object is not in an inconsistent state.\n self._sky_coord_frame[item] = value._sky_coord_frame\n\n def insert(self, obj, values, axis=0):\n \"\"\"\n Insert coordinate values before the given indices in the object and\n return a new Frame object.\n\n The values to be inserted must conform to the rules for in-place setting\n of ``SkyCoord`` objects.\n\n The API signature matches the ``np.insert`` API, but is more limited.\n The specification of insert index ``obj`` must be a single integer,\n and the ``axis`` must be ``0`` for simple insertion before the index.\n\n Parameters\n ----------\n obj : int\n Integer index before which ``values`` is inserted.\n values : array_like\n Value(s) to insert. If the type of ``values`` is different\n from that of quantity, ``values`` is converted to the matching type.\n axis : int, optional\n Axis along which to insert ``values``. Default is 0, which is the\n only allowed value and will insert a row.\n\n Returns\n -------\n out : `~astropy.coordinates.SkyCoord` instance\n New coordinate object with inserted value(s)\n\n \"\"\"\n # Validate inputs: obj arg is integer, axis=0, self is not a scalar, and\n # input index is in bounds.\n try:\n idx0 = operator.index(obj)\n except TypeError:\n raise TypeError('obj arg must be an integer')\n\n if axis != 0:\n raise ValueError('axis must be 0')\n\n if not self.shape:\n raise TypeError('cannot insert into scalar {} object'\n .format(self.__class__.__name__))\n\n if abs(idx0) > len(self):\n raise IndexError('index {} is out of bounds for axis 0 with size {}'\n .format(idx0, len(self)))\n\n # Turn negative index into positive\n if idx0 < 0:\n idx0 = len(self) + idx0\n\n n_values = len(values) if values.shape else 1\n\n # Finally make the new object with the correct length and set values for the\n # three sections, before insert, the insert, and after the insert.\n out = self.__class__.info.new_like([self], len(self) + n_values, name=self.info.name)\n\n # Set the output values. This is where validation of `values` takes place to ensure\n # that it can indeed be inserted.\n out[:idx0] = self[:idx0]\n out[idx0:idx0 + n_values] = values\n out[idx0 + n_values:] = self[idx0:]\n\n return out\n\n def transform_to(self, frame, merge_attributes=True):\n \"\"\"Transform this coordinate to a new frame.\n\n The precise frame transformed to depends on ``merge_attributes``.\n If `False`, the destination frame is used exactly as passed in.\n But this is often not quite what one wants. E.g., suppose one wants to\n transform an ICRS coordinate that has an obstime attribute to FK4; in\n this case, one likely would want to use this information. Thus, the\n default for ``merge_attributes`` is `True`, in which the precedence is\n as follows: (1) explicitly set (i.e., non-default) values in the\n destination frame; (2) explicitly set values in the source; (3) default\n value in the destination frame.\n\n Note that in either case, any explicitly set attributes on the source\n `SkyCoord` that are not part of the destination frame's definition are\n kept (stored on the resulting `SkyCoord`), and thus one can round-trip\n (e.g., from FK4 to ICRS to FK4 without loosing obstime).\n\n Parameters\n ----------\n frame : str, `BaseCoordinateFrame` class or instance, or `SkyCoord` instance\n The frame to transform this coordinate into. If a `SkyCoord`, the\n underlying frame is extracted, and all other information ignored.\n merge_attributes : bool, optional\n Whether the default attributes in the destination frame are allowed\n to be overridden by explicitly set attributes in the source\n (see note above; default: `True`).\n\n Returns\n -------\n coord : `SkyCoord`\n A new object with this coordinate represented in the `frame` frame.\n\n Raises\n ------\n ValueError\n If there is no possible transformation route.\n\n \"\"\"\n from astropy.coordinates.errors import ConvertError\n\n frame_kwargs = {}\n\n # Frame name (string) or frame class? Coerce into an instance.\n try:\n frame = _get_frame_class(frame)()\n except Exception:\n pass\n\n if isinstance(frame, SkyCoord):\n frame = frame.frame # Change to underlying coord frame instance\n\n if isinstance(frame, BaseCoordinateFrame):\n new_frame_cls = frame.__class__\n # Get frame attributes, allowing defaults to be overridden by\n # explicitly set attributes of the source if ``merge_attributes``.\n for attr in frame_transform_graph.frame_attributes:\n self_val = getattr(self, attr, None)\n frame_val = getattr(frame, attr, None)\n if (frame_val is not None\n and not (merge_attributes\n and frame.is_frame_attr_default(attr))):\n frame_kwargs[attr] = frame_val\n elif (self_val is not None\n and not self.is_frame_attr_default(attr)):\n frame_kwargs[attr] = self_val\n elif frame_val is not None:\n frame_kwargs[attr] = frame_val\n else:\n raise ValueError('Transform `frame` must be a frame name, class, or instance')\n\n # Get the composite transform to the new frame\n trans = frame_transform_graph.get_transform(self.frame.__class__, new_frame_cls)\n if trans is None:\n raise ConvertError('Cannot transform from {} to {}'\n .format(self.frame.__class__, new_frame_cls))\n\n # Make a generic frame which will accept all the frame kwargs that\n # are provided and allow for transforming through intermediate frames\n # which may require one or more of those kwargs.\n generic_frame = GenericFrame(frame_kwargs)\n\n # Do the transformation, returning a coordinate frame of the desired\n # final type (not generic).\n new_coord = trans(self.frame, generic_frame)\n\n # Finally make the new SkyCoord object from the `new_coord` and\n # remaining frame_kwargs that are not frame_attributes in `new_coord`.\n for attr in (set(new_coord.get_frame_attr_names()) &\n set(frame_kwargs.keys())):\n frame_kwargs.pop(attr)\n\n return self.__class__(new_coord, **frame_kwargs)\n\n def apply_space_motion(self, new_obstime=None, dt=None):\n \"\"\"\n Compute the position of the source represented by this coordinate object\n to a new time using the velocities stored in this object and assuming\n linear space motion (including relativistic corrections). This is\n sometimes referred to as an \"epoch transformation.\"\n\n The initial time before the evolution is taken from the ``obstime``\n attribute of this coordinate. Note that this method currently does not\n support evolving coordinates where the *frame* has an ``obstime`` frame\n attribute, so the ``obstime`` is only used for storing the before and\n after times, not actually as an attribute of the frame. Alternatively,\n if ``dt`` is given, an ``obstime`` need not be provided at all.\n\n Parameters\n ----------\n new_obstime : `~astropy.time.Time`, optional\n The time at which to evolve the position to. Requires that the\n ``obstime`` attribute be present on this frame.\n dt : `~astropy.units.Quantity`, `~astropy.time.TimeDelta`, optional\n An amount of time to evolve the position of the source. Cannot be\n given at the same time as ``new_obstime``.\n\n Returns\n -------\n new_coord : `SkyCoord`\n A new coordinate object with the evolved location of this coordinate\n at the new time. ``obstime`` will be set on this object to the new\n time only if ``self`` also has ``obstime``.\n \"\"\"\n\n if (new_obstime is None and dt is None or\n new_obstime is not None and dt is not None):\n raise ValueError(\"You must specify one of `new_obstime` or `dt`, \"\n \"but not both.\")\n\n # Validate that we have velocity info\n if 's' not in self.frame.data.differentials:\n raise ValueError('SkyCoord requires velocity data to evolve the '\n 'position.')\n\n if 'obstime' in self.frame.frame_attributes:\n raise NotImplementedError(\"Updating the coordinates in a frame \"\n \"with explicit time dependence is \"\n \"currently not supported. If you would \"\n \"like this functionality, please open an \"\n \"issue on github:\\n\"\n \"https://github.com/astropy/astropy\")\n\n if new_obstime is not None and self.obstime is None:\n # If no obstime is already on this object, raise an error if a new\n # obstime is passed: we need to know the time / epoch at which the\n # the position / velocity were measured initially\n raise ValueError('This object has no associated `obstime`. '\n 'apply_space_motion() must receive a time '\n 'difference, `dt`, and not a new obstime.')\n\n # Compute t1 and t2, the times used in the starpm call, which *only*\n # uses them to compute a delta-time\n t1 = self.obstime\n if dt is None:\n # self.obstime is not None and new_obstime is not None b/c of above\n # checks\n t2 = new_obstime\n else:\n # new_obstime is definitely None b/c of the above checks\n if t1 is None:\n # MAGIC NUMBER: if the current SkyCoord object has no obstime,\n # assume J2000 to do the dt offset. This is not actually used\n # for anything except a delta-t in starpm, so it's OK that it's\n # not necessarily the \"real\" obstime\n t1 = Time('J2000')\n new_obstime = None # we don't actually know the inital obstime\n t2 = t1 + dt\n else:\n t2 = t1 + dt\n new_obstime = t2\n # starpm wants tdb time\n t1 = t1.tdb\n t2 = t2.tdb\n\n # proper motion in RA should not include the cos(dec) term, see the\n # erfa function eraStarpv, comment (4). So we convert to the regular\n # spherical differentials.\n icrsrep = self.icrs.represent_as(SphericalRepresentation, SphericalDifferential)\n icrsvel = icrsrep.differentials['s']\n\n parallax_zero = False\n try:\n plx = icrsrep.distance.to_value(u.arcsecond, u.parallax())\n except u.UnitConversionError: # No distance: set to 0 by convention\n plx = 0.\n parallax_zero = True\n\n try:\n rv = icrsvel.d_distance.to_value(u.km/u.s)\n except u.UnitConversionError: # No RV\n rv = 0.\n\n starpm = erfa.pmsafe(icrsrep.lon.radian, icrsrep.lat.radian,\n icrsvel.d_lon.to_value(u.radian/u.yr),\n icrsvel.d_lat.to_value(u.radian/u.yr),\n plx, rv, t1.jd1, t1.jd2, t2.jd1, t2.jd2)\n\n if parallax_zero:\n new_distance = None\n else:\n new_distance = Distance(parallax=starpm[4] << u.arcsec)\n\n icrs2 = ICRS(ra=u.Quantity(starpm[0], u.radian, copy=False),\n dec=u.Quantity(starpm[1], u.radian, copy=False),\n pm_ra=u.Quantity(starpm[2], u.radian/u.yr, copy=False),\n pm_dec=u.Quantity(starpm[3], u.radian/u.yr, copy=False),\n distance=new_distance,\n radial_velocity=u.Quantity(starpm[5], u.km/u.s, copy=False),\n differential_type=SphericalDifferential)\n\n # Update the obstime of the returned SkyCoord, and need to carry along\n # the frame attributes\n frattrs = {attrnm: getattr(self, attrnm)\n for attrnm in self._extra_frameattr_names}\n frattrs['obstime'] = new_obstime\n return self.__class__(icrs2, **frattrs).transform_to(self.frame)\n\n def _is_name(self, string):\n \"\"\"\n Returns whether a string is one of the aliases for the frame.\n \"\"\"\n return (self.frame.name == string or\n (isinstance(self.frame.name, list) and string in self.frame.name))\n\n def __getattr__(self, attr):\n \"\"\"\n Overrides getattr to return coordinates that this can be transformed\n to, based on the alias attr in the master transform graph.\n \"\"\"\n if '_sky_coord_frame' in self.__dict__:\n if self._is_name(attr):\n return self # Should this be a deepcopy of self?\n\n # Anything in the set of all possible frame_attr_names is handled\n # here. If the attr is relevant for the current frame then delegate\n # to self.frame otherwise get it from self._<attr>.\n if attr in frame_transform_graph.frame_attributes:\n if attr in self.frame.get_frame_attr_names():\n return getattr(self.frame, attr)\n else:\n return getattr(self, '_' + attr, None)\n\n # Some attributes might not fall in the above category but still\n # are available through self._sky_coord_frame.\n if not attr.startswith('_') and hasattr(self._sky_coord_frame, attr):\n return getattr(self._sky_coord_frame, attr)\n\n # Try to interpret as a new frame for transforming.\n frame_cls = frame_transform_graph.lookup_name(attr)\n if frame_cls is not None and self.frame.is_transformable_to(frame_cls):\n return self.transform_to(attr)\n\n # Fail\n raise AttributeError(\"'{}' object has no attribute '{}'\"\n .format(self.__class__.__name__, attr))\n\n def __setattr__(self, attr, val):\n # This is to make anything available through __getattr__ immutable\n if '_sky_coord_frame' in self.__dict__:\n if self._is_name(attr):\n raise AttributeError(f\"'{attr}' is immutable\")\n\n if not attr.startswith('_') and hasattr(self._sky_coord_frame, attr):\n setattr(self._sky_coord_frame, attr, val)\n return\n\n frame_cls = frame_transform_graph.lookup_name(attr)\n if frame_cls is not None and self.frame.is_transformable_to(frame_cls):\n raise AttributeError(f\"'{attr}' is immutable\")\n\n if attr in frame_transform_graph.frame_attributes:\n # All possible frame attributes can be set, but only via a private\n # variable. See __getattr__ above.\n super().__setattr__('_' + attr, val)\n # Validate it\n frame_transform_graph.frame_attributes[attr].__get__(self)\n # And add to set of extra attributes\n self._extra_frameattr_names |= {attr}\n\n else:\n # Otherwise, do the standard Python attribute setting\n super().__setattr__(attr, val)\n\n def __delattr__(self, attr):\n # mirror __setattr__ above\n if '_sky_coord_frame' in self.__dict__:\n if self._is_name(attr):\n raise AttributeError(f\"'{attr}' is immutable\")\n\n if not attr.startswith('_') and hasattr(self._sky_coord_frame,\n attr):\n delattr(self._sky_coord_frame, attr)\n return\n\n frame_cls = frame_transform_graph.lookup_name(attr)\n if frame_cls is not None and self.frame.is_transformable_to(frame_cls):\n raise AttributeError(f\"'{attr}' is immutable\")\n\n if attr in frame_transform_graph.frame_attributes:\n # All possible frame attributes can be deleted, but need to remove\n # the corresponding private variable. See __getattr__ above.\n super().__delattr__('_' + attr)\n # Also remove it from the set of extra attributes\n self._extra_frameattr_names -= {attr}\n\n else:\n # Otherwise, do the standard Python attribute setting\n super().__delattr__(attr)\n\n @override__dir__\n def __dir__(self):\n \"\"\"\n Override the builtin `dir` behavior to include:\n - Transforms available by aliases\n - Attribute / methods of the underlying self.frame object\n \"\"\"\n\n # determine the aliases that this can be transformed to.\n dir_values = set()\n for name in frame_transform_graph.get_names():\n frame_cls = frame_transform_graph.lookup_name(name)\n if self.frame.is_transformable_to(frame_cls):\n dir_values.add(name)\n\n # Add public attributes of self.frame\n dir_values.update(set(attr for attr in dir(self.frame) if not attr.startswith('_')))\n\n # Add all possible frame attributes\n dir_values.update(frame_transform_graph.frame_attributes.keys())\n\n return dir_values\n\n def __repr__(self):\n clsnm = self.__class__.__name__\n coonm = self.frame.__class__.__name__\n frameattrs = self.frame._frame_attrs_repr()\n if frameattrs:\n frameattrs = ': ' + frameattrs\n\n data = self.frame._data_repr()\n if data:\n data = ': ' + data\n\n return '<{clsnm} ({coonm}{frameattrs}){data}>'.format(**locals())\n\n def to_string(self, style='decimal', **kwargs):\n \"\"\"\n A string representation of the coordinates.\n\n The default styles definitions are::\n\n 'decimal': 'lat': {'decimal': True, 'unit': \"deg\"}\n 'lon': {'decimal': True, 'unit': \"deg\"}\n 'dms': 'lat': {'unit': \"deg\"}\n 'lon': {'unit': \"deg\"}\n 'hmsdms': 'lat': {'alwayssign': True, 'pad': True, 'unit': \"deg\"}\n 'lon': {'pad': True, 'unit': \"hour\"}\n\n See :meth:`~astropy.coordinates.Angle.to_string` for details and\n keyword arguments (the two angles forming the coordinates are are\n both :class:`~astropy.coordinates.Angle` instances). Keyword\n arguments have precedence over the style defaults and are passed\n to :meth:`~astropy.coordinates.Angle.to_string`.\n\n Parameters\n ----------\n style : {'hmsdms', 'dms', 'decimal'}\n The formatting specification to use. These encode the three most\n common ways to represent coordinates. The default is `decimal`.\n kwargs\n Keyword args passed to :meth:`~astropy.coordinates.Angle.to_string`.\n \"\"\"\n\n sph_coord = self.frame.represent_as(SphericalRepresentation)\n\n styles = {'hmsdms': {'lonargs': {'unit': u.hour, 'pad': True},\n 'latargs': {'unit': u.degree, 'pad': True, 'alwayssign': True}},\n 'dms': {'lonargs': {'unit': u.degree},\n 'latargs': {'unit': u.degree}},\n 'decimal': {'lonargs': {'unit': u.degree, 'decimal': True},\n 'latargs': {'unit': u.degree, 'decimal': True}}\n }\n\n lonargs = {}\n latargs = {}\n\n if style in styles:\n lonargs.update(styles[style]['lonargs'])\n latargs.update(styles[style]['latargs'])\n else:\n raise ValueError('Invalid style. Valid options are: {}'.format(\",\".join(styles)))\n\n lonargs.update(kwargs)\n latargs.update(kwargs)\n\n if np.isscalar(sph_coord.lon.value):\n coord_string = (sph_coord.lon.to_string(**lonargs) +\n \" \" + sph_coord.lat.to_string(**latargs))\n else:\n coord_string = []\n for lonangle, latangle in zip(sph_coord.lon.ravel(), sph_coord.lat.ravel()):\n coord_string += [(lonangle.to_string(**lonargs) +\n \" \" + latangle.to_string(**latargs))]\n if len(sph_coord.shape) > 1:\n coord_string = np.array(coord_string).reshape(sph_coord.shape)\n\n return coord_string\n\n def is_equivalent_frame(self, other):\n \"\"\"\n Checks if this object's frame as the same as that of the ``other``\n object.\n\n To be the same frame, two objects must be the same frame class and have\n the same frame attributes. For two `SkyCoord` objects, *all* of the\n frame attributes have to match, not just those relevant for the object's\n frame.\n\n Parameters\n ----------\n other : SkyCoord or BaseCoordinateFrame\n The other object to check.\n\n Returns\n -------\n isequiv : bool\n True if the frames are the same, False if not.\n\n Raises\n ------\n TypeError\n If ``other`` isn't a `SkyCoord` or a `BaseCoordinateFrame` or subclass.\n \"\"\"\n if isinstance(other, BaseCoordinateFrame):\n return self.frame.is_equivalent_frame(other)\n elif isinstance(other, SkyCoord):\n if other.frame.name != self.frame.name:\n return False\n\n for fattrnm in frame_transform_graph.frame_attributes:\n if not BaseCoordinateFrame._frameattr_equiv(getattr(self, fattrnm),\n getattr(other, fattrnm)):\n return False\n return True\n else:\n # not a BaseCoordinateFrame nor a SkyCoord object\n raise TypeError(\"Tried to do is_equivalent_frame on something that \"\n \"isn't frame-like\")\n\n # High-level convenience methods\n def separation(self, other):\n \"\"\"\n Computes on-sky separation between this coordinate and another.\n\n .. note::\n\n If the ``other`` coordinate object is in a different frame, it is\n first transformed to the frame of this object. This can lead to\n unintuitive behavior if not accounted for. Particularly of note is\n that ``self.separation(other)`` and ``other.separation(self)`` may\n not give the same answer in this case.\n\n For more on how to use this (and related) functionality, see the\n examples in :doc:`/coordinates/matchsep`.\n\n Parameters\n ----------\n other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`\n The coordinate to get the separation to.\n\n Returns\n -------\n sep : `~astropy.coordinates.Angle`\n The on-sky separation between this and the ``other`` coordinate.\n\n Notes\n -----\n The separation is calculated using the Vincenty formula, which\n is stable at all locations, including poles and antipodes [1]_.\n\n .. [1] https://en.wikipedia.org/wiki/Great-circle_distance\n\n \"\"\"\n from . import Angle\n from .angle_utilities import angular_separation\n\n if not self.is_equivalent_frame(other):\n try:\n kwargs = {'merge_attributes': False} if isinstance(other, SkyCoord) else {}\n other = other.transform_to(self, **kwargs)\n except TypeError:\n raise TypeError('Can only get separation to another SkyCoord '\n 'or a coordinate frame with data')\n\n lon1 = self.spherical.lon\n lat1 = self.spherical.lat\n lon2 = other.spherical.lon\n lat2 = other.spherical.lat\n\n # Get the separation as a Quantity, convert to Angle in degrees\n sep = angular_separation(lon1, lat1, lon2, lat2)\n return Angle(sep, unit=u.degree)\n\n def separation_3d(self, other):\n \"\"\"\n Computes three dimensional separation between this coordinate\n and another.\n\n For more on how to use this (and related) functionality, see the\n examples in :doc:`/coordinates/matchsep`.\n\n Parameters\n ----------\n other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`\n The coordinate to get the separation to.\n\n Returns\n -------\n sep : `~astropy.coordinates.Distance`\n The real-space distance between these two coordinates.\n\n Raises\n ------\n ValueError\n If this or the other coordinate do not have distances.\n \"\"\"\n if not self.is_equivalent_frame(other):\n try:\n kwargs = {'merge_attributes': False} if isinstance(other, SkyCoord) else {}\n other = other.transform_to(self, **kwargs)\n except TypeError:\n raise TypeError('Can only get separation to another SkyCoord '\n 'or a coordinate frame with data')\n\n if issubclass(self.data.__class__, UnitSphericalRepresentation):\n raise ValueError('This object does not have a distance; cannot '\n 'compute 3d separation.')\n if issubclass(other.data.__class__, UnitSphericalRepresentation):\n raise ValueError('The other object does not have a distance; '\n 'cannot compute 3d separation.')\n\n c1 = self.cartesian.without_differentials()\n c2 = other.cartesian.without_differentials()\n return Distance((c1 - c2).norm())\n\n def spherical_offsets_to(self, tocoord):\n r\"\"\"\n Computes angular offsets to go *from* this coordinate *to* another.\n\n Parameters\n ----------\n tocoord : `~astropy.coordinates.BaseCoordinateFrame`\n The coordinate to find the offset to.\n\n Returns\n -------\n lon_offset : `~astropy.coordinates.Angle`\n The angular offset in the longitude direction (i.e., RA for\n equatorial coordinates).\n lat_offset : `~astropy.coordinates.Angle`\n The angular offset in the latitude direction (i.e., Dec for\n equatorial coordinates).\n\n Raises\n ------\n ValueError\n If the ``tocoord`` is not in the same frame as this one. This is\n different from the behavior of the `separation`/`separation_3d`\n methods because the offset components depend critically on the\n specific choice of frame.\n\n Notes\n -----\n This uses the sky offset frame machinery, and hence will produce a new\n sky offset frame if one does not already exist for this object's frame\n class.\n\n See Also\n --------\n separation : for the *total* angular offset (not broken out into components).\n position_angle : for the direction of the offset.\n\n \"\"\"\n if not self.is_equivalent_frame(tocoord):\n raise ValueError('Tried to use spherical_offsets_to with two non-matching frames!')\n\n aframe = self.skyoffset_frame()\n acoord = tocoord.transform_to(aframe)\n\n dlon = acoord.spherical.lon.view(Angle)\n dlat = acoord.spherical.lat.view(Angle)\n return dlon, dlat\n\n def directional_offset_by(self, position_angle, separation):\n \"\"\"\n Computes coordinates at the given offset from this coordinate.\n\n Parameters\n ----------\n position_angle : `~astropy.coordinates.Angle`\n position_angle of offset\n separation : `~astropy.coordinates.Angle`\n offset angular separation\n\n Returns\n -------\n newpoints : `~astropy.coordinates.SkyCoord`\n The coordinates for the location that corresponds to offsetting by\n the given `position_angle` and `separation`.\n\n Notes\n -----\n Returned SkyCoord frame retains only the frame attributes that are for\n the resulting frame type. (e.g. if the input frame is\n `~astropy.coordinates.ICRS`, an ``equinox`` value will be retained, but\n an ``obstime`` will not.)\n\n For a more complete set of transform offsets, use `~astropy.wcs.WCS`.\n `~astropy.coordinates.SkyCoord.skyoffset_frame()` can also be used to\n create a spherical frame with (lat=0, lon=0) at a reference point,\n approximating an xy cartesian system for small offsets. This method\n is distinct in that it is accurate on the sphere.\n\n See Also\n --------\n position_angle : inverse operation for the ``position_angle`` component\n separation : inverse operation for the ``separation`` component\n\n \"\"\"\n from . import angle_utilities\n\n slat = self.represent_as(UnitSphericalRepresentation).lat\n slon = self.represent_as(UnitSphericalRepresentation).lon\n\n newlon, newlat = angle_utilities.offset_by(\n lon=slon, lat=slat,\n posang=position_angle, distance=separation)\n\n return SkyCoord(newlon, newlat, frame=self.frame)\n\n def match_to_catalog_sky(self, catalogcoord, nthneighbor=1):\n \"\"\"\n Finds the nearest on-sky matches of this coordinate in a set of\n catalog coordinates.\n\n For more on how to use this (and related) functionality, see the\n examples in :doc:`/coordinates/matchsep`.\n\n Parameters\n ----------\n catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`\n The base catalog in which to search for matches. Typically this\n will be a coordinate object that is an array (i.e.,\n ``catalogcoord.isscalar == False``)\n nthneighbor : int, optional\n Which closest neighbor to search for. Typically ``1`` is\n desired here, as that is correct for matching one set of\n coordinates to another. The next likely use case is ``2``,\n for matching a coordinate catalog against *itself* (``1``\n is inappropriate because each point will find itself as the\n closest match).\n\n Returns\n -------\n idx : integer array\n Indices into ``catalogcoord`` to get the matched points for\n each of this object's coordinates. Shape matches this\n object.\n sep2d : `~astropy.coordinates.Angle`\n The on-sky separation between the closest match for each\n element in this object in ``catalogcoord``. Shape matches\n this object.\n dist3d : `~astropy.units.Quantity`\n The 3D distance between the closest match for each element\n in this object in ``catalogcoord``. Shape matches this\n object. Unless both this and ``catalogcoord`` have associated\n distances, this quantity assumes that all sources are at a\n distance of 1 (dimensionless).\n\n Notes\n -----\n This method requires `SciPy <https://www.scipy.org/>`_ to be\n installed or it will fail.\n\n See Also\n --------\n astropy.coordinates.match_coordinates_sky\n SkyCoord.match_to_catalog_3d\n \"\"\"\n from .matching import match_coordinates_sky\n\n if (isinstance(catalogcoord, (SkyCoord, BaseCoordinateFrame))\n and catalogcoord.has_data):\n self_in_catalog_frame = self.transform_to(catalogcoord)\n else:\n raise TypeError('Can only get separation to another SkyCoord or a '\n 'coordinate frame with data')\n\n res = match_coordinates_sky(self_in_catalog_frame, catalogcoord,\n nthneighbor=nthneighbor,\n storekdtree='_kdtree_sky')\n return res\n\n def match_to_catalog_3d(self, catalogcoord, nthneighbor=1):\n \"\"\"\n Finds the nearest 3-dimensional matches of this coordinate to a set\n of catalog coordinates.\n\n This finds the 3-dimensional closest neighbor, which is only different\n from the on-sky distance if ``distance`` is set in this object or the\n ``catalogcoord`` object.\n\n For more on how to use this (and related) functionality, see the\n examples in :doc:`/coordinates/matchsep`.\n\n Parameters\n ----------\n catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`\n The base catalog in which to search for matches. Typically this\n will be a coordinate object that is an array (i.e.,\n ``catalogcoord.isscalar == False``)\n nthneighbor : int, optional\n Which closest neighbor to search for. Typically ``1`` is\n desired here, as that is correct for matching one set of\n coordinates to another. The next likely use case is\n ``2``, for matching a coordinate catalog against *itself*\n (``1`` is inappropriate because each point will find\n itself as the closest match).\n\n Returns\n -------\n idx : integer array\n Indices into ``catalogcoord`` to get the matched points for\n each of this object's coordinates. Shape matches this\n object.\n sep2d : `~astropy.coordinates.Angle`\n The on-sky separation between the closest match for each\n element in this object in ``catalogcoord``. Shape matches\n this object.\n dist3d : `~astropy.units.Quantity`\n The 3D distance between the closest match for each element\n in this object in ``catalogcoord``. Shape matches this\n object.\n\n Notes\n -----\n This method requires `SciPy <https://www.scipy.org/>`_ to be\n installed or it will fail.\n\n See Also\n --------\n astropy.coordinates.match_coordinates_3d\n SkyCoord.match_to_catalog_sky\n \"\"\"\n from .matching import match_coordinates_3d\n\n if (isinstance(catalogcoord, (SkyCoord, BaseCoordinateFrame))\n and catalogcoord.has_data):\n self_in_catalog_frame = self.transform_to(catalogcoord)\n else:\n raise TypeError('Can only get separation to another SkyCoord or a '\n 'coordinate frame with data')\n\n res = match_coordinates_3d(self_in_catalog_frame, catalogcoord,\n nthneighbor=nthneighbor,\n storekdtree='_kdtree_3d')\n\n return res\n\n def search_around_sky(self, searcharoundcoords, seplimit):\n \"\"\"\n Searches for all coordinates in this object around a supplied set of\n points within a given on-sky separation.\n\n This is intended for use on `~astropy.coordinates.SkyCoord` objects\n with coordinate arrays, rather than a scalar coordinate. For a scalar\n coordinate, it is better to use\n `~astropy.coordinates.SkyCoord.separation`.\n\n For more on how to use this (and related) functionality, see the\n examples in :doc:`/coordinates/matchsep`.\n\n Parameters\n ----------\n searcharoundcoords : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`\n The coordinates to search around to try to find matching points in\n this `SkyCoord`. This should be an object with array coordinates,\n not a scalar coordinate object.\n seplimit : `~astropy.units.Quantity` with angle units\n The on-sky separation to search within.\n\n Returns\n -------\n idxsearcharound : integer array\n Indices into ``searcharoundcoords`` that match the\n corresponding elements of ``idxself``. Shape matches\n ``idxself``.\n idxself : integer array\n Indices into ``self`` that match the\n corresponding elements of ``idxsearcharound``. Shape matches\n ``idxsearcharound``.\n sep2d : `~astropy.coordinates.Angle`\n The on-sky separation between the coordinates. Shape matches\n ``idxsearcharound`` and ``idxself``.\n dist3d : `~astropy.units.Quantity`\n The 3D distance between the coordinates. Shape matches\n ``idxsearcharound`` and ``idxself``.\n\n Notes\n -----\n This method requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be\n installed or it will fail.\n\n In the current implementation, the return values are always sorted in\n the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is\n in ascending order). This is considered an implementation detail,\n though, so it could change in a future release.\n\n See Also\n --------\n astropy.coordinates.search_around_sky\n SkyCoord.search_around_3d\n \"\"\"\n from .matching import search_around_sky\n\n return search_around_sky(searcharoundcoords, self, seplimit,\n storekdtree='_kdtree_sky')\n\n def search_around_3d(self, searcharoundcoords, distlimit):\n \"\"\"\n Searches for all coordinates in this object around a supplied set of\n points within a given 3D radius.\n\n This is intended for use on `~astropy.coordinates.SkyCoord` objects\n with coordinate arrays, rather than a scalar coordinate. For a scalar\n coordinate, it is better to use\n `~astropy.coordinates.SkyCoord.separation_3d`.\n\n For more on how to use this (and related) functionality, see the\n examples in :doc:`/coordinates/matchsep`.\n\n Parameters\n ----------\n searcharoundcoords : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame`\n The coordinates to search around to try to find matching points in\n this `SkyCoord`. This should be an object with array coordinates,\n not a scalar coordinate object.\n distlimit : `~astropy.units.Quantity` with distance units\n The physical radius to search within.\n\n Returns\n -------\n idxsearcharound : integer array\n Indices into ``searcharoundcoords`` that match the\n corresponding elements of ``idxself``. Shape matches\n ``idxself``.\n idxself : integer array\n Indices into ``self`` that match the\n corresponding elements of ``idxsearcharound``. Shape matches\n ``idxsearcharound``.\n sep2d : `~astropy.coordinates.Angle`\n The on-sky separation between the coordinates. Shape matches\n ``idxsearcharound`` and ``idxself``.\n dist3d : `~astropy.units.Quantity`\n The 3D distance between the coordinates. Shape matches\n ``idxsearcharound`` and ``idxself``.\n\n Notes\n -----\n This method requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be\n installed or it will fail.\n\n In the current implementation, the return values are always sorted in\n the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is\n in ascending order). This is considered an implementation detail,\n though, so it could change in a future release.\n\n See Also\n --------\n astropy.coordinates.search_around_3d\n SkyCoord.search_around_sky\n \"\"\"\n from .matching import search_around_3d\n\n return search_around_3d(searcharoundcoords, self, distlimit,\n storekdtree='_kdtree_3d')\n\n def position_angle(self, other):\n \"\"\"\n Computes the on-sky position angle (East of North) between this\n `SkyCoord` and another.\n\n Parameters\n ----------\n other : `SkyCoord`\n The other coordinate to compute the position angle to. It is\n treated as the \"head\" of the vector of the position angle.\n\n Returns\n -------\n pa : `~astropy.coordinates.Angle`\n The (positive) position angle of the vector pointing from ``self``\n to ``other``. If either ``self`` or ``other`` contain arrays, this\n will be an array following the appropriate `numpy` broadcasting\n rules.\n\n Examples\n --------\n\n >>> c1 = SkyCoord(0*u.deg, 0*u.deg)\n >>> c2 = SkyCoord(1*u.deg, 0*u.deg)\n >>> c1.position_angle(c2).degree\n 90.0\n >>> c3 = SkyCoord(1*u.deg, 1*u.deg)\n >>> c1.position_angle(c3).degree # doctest: +FLOAT_CMP\n 44.995636455344844\n \"\"\"\n from . import angle_utilities\n\n if not self.is_equivalent_frame(other):\n try:\n other = other.transform_to(self, merge_attributes=False)\n except TypeError:\n raise TypeError('Can only get position_angle to another '\n 'SkyCoord or a coordinate frame with data')\n\n slat = self.represent_as(UnitSphericalRepresentation).lat\n slon = self.represent_as(UnitSphericalRepresentation).lon\n olat = other.represent_as(UnitSphericalRepresentation).lat\n olon = other.represent_as(UnitSphericalRepresentation).lon\n\n return angle_utilities.position_angle(slon, slat, olon, olat)\n\n def skyoffset_frame(self, rotation=None):\n \"\"\"\n Returns the sky offset frame with this `SkyCoord` at the origin.\n\n Returns\n -------\n astrframe : `~astropy.coordinates.SkyOffsetFrame`\n A sky offset frame of the same type as this `SkyCoord` (e.g., if\n this object has an ICRS coordinate, the resulting frame is\n SkyOffsetICRS, with the origin set to this object)\n rotation : `~astropy.coordinates.Angle` or `~astropy.units.Quantity` with angle units\n The final rotation of the frame about the ``origin``. The sign of\n the rotation is the left-hand rule. That is, an object at a\n particular position angle in the un-rotated system will be sent to\n the positive latitude (z) direction in the final frame.\n \"\"\"\n return SkyOffsetFrame(origin=self, rotation=rotation)\n\n def get_constellation(self, short_name=False, constellation_list='iau'):\n \"\"\"\n Determines the constellation(s) of the coordinates this `SkyCoord`\n contains.\n\n Parameters\n ----------\n short_name : bool\n If True, the returned names are the IAU-sanctioned abbreviated\n names. Otherwise, full names for the constellations are used.\n constellation_list : str\n The set of constellations to use. Currently only ``'iau'`` is\n supported, meaning the 88 \"modern\" constellations endorsed by the IAU.\n\n Returns\n -------\n constellation : str or string array\n If this is a scalar coordinate, returns the name of the\n constellation. If it is an array `SkyCoord`, it returns an array of\n names.\n\n Notes\n -----\n To determine which constellation a point on the sky is in, this first\n precesses to B1875, and then uses the Delporte boundaries of the 88\n modern constellations, as tabulated by\n `Roman 1987 <http://cdsarc.u-strasbg.fr/viz-bin/Cat?VI/42>`_.\n\n See Also\n --------\n astropy.coordinates.get_constellation\n \"\"\"\n from .funcs import get_constellation\n\n # because of issue #7028, the conversion to a PrecessedGeocentric\n # system fails in some cases. Work around is to drop the velocities.\n # they are not needed here since only position infromation is used\n extra_frameattrs = {nm: getattr(self, nm)\n for nm in self._extra_frameattr_names}\n novel = SkyCoord(self.realize_frame(self.data.without_differentials()),\n **extra_frameattrs)\n return get_constellation(novel, short_name, constellation_list)\n\n # the simpler version below can be used when gh-issue #7028 is resolved\n # return get_constellation(self, short_name, constellation_list)\n\n # WCS pixel to/from sky conversions\n def to_pixel(self, wcs, origin=0, mode='all'):\n \"\"\"\n Convert this coordinate to pixel coordinates using a `~astropy.wcs.WCS`\n object.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The WCS to use for convert\n origin : int\n Whether to return 0 or 1-based pixel coordinates.\n mode : 'all' or 'wcs'\n Whether to do the transformation including distortions (``'all'``) or\n only including only the core WCS transformation (``'wcs'``).\n\n Returns\n -------\n xp, yp : `numpy.ndarray`\n The pixel coordinates\n\n See Also\n --------\n astropy.wcs.utils.skycoord_to_pixel : the implementation of this method\n \"\"\"\n from astropy.wcs.utils import skycoord_to_pixel\n return skycoord_to_pixel(self, wcs=wcs, origin=origin, mode=mode)\n\n @classmethod\n def from_pixel(cls, xp, yp, wcs, origin=0, mode='all'):\n \"\"\"\n Create a new `SkyCoord` from pixel coordinates using an\n `~astropy.wcs.WCS` object.\n\n Parameters\n ----------\n xp, yp : float or `numpy.ndarray`\n The coordinates to convert.\n wcs : `~astropy.wcs.WCS`\n The WCS to use for convert\n origin : int\n Whether to return 0 or 1-based pixel coordinates.\n mode : 'all' or 'wcs'\n Whether to do the transformation including distortions (``'all'``) or\n only including only the core WCS transformation (``'wcs'``).\n\n Returns\n -------\n coord : an instance of this class\n A new object with sky coordinates corresponding to the input ``xp``\n and ``yp``.\n\n See Also\n --------\n to_pixel : to do the inverse operation\n astropy.wcs.utils.pixel_to_skycoord : the implementation of this method\n \"\"\"\n from astropy.wcs.utils import pixel_to_skycoord\n return pixel_to_skycoord(xp, yp, wcs=wcs, origin=origin, mode=mode, cls=cls)\n\n def contained_by(self, wcs, image=None, **kwargs):\n \"\"\"\n Determines if the SkyCoord is contained in the given wcs footprint.\n\n Parameters\n ----------\n wcs : `~astropy.wcs.WCS`\n The coordinate to check if it is within the wcs coordinate.\n image : array\n Optional. The image associated with the wcs object that the cooordinate\n is being checked against. If not given the naxis keywords will be used\n to determine if the coordinate falls within the wcs footprint.\n **kwargs :\n Additional arguments to pass to `~astropy.coordinates.SkyCoord.to_pixel`\n\n Returns\n -------\n response : bool\n True means the WCS footprint contains the coordinate, False means it does not.\n \"\"\"\n\n if image is not None:\n ymax, xmax = image.shape\n else:\n xmax, ymax = wcs._naxis\n\n import warnings\n with warnings.catch_warnings():\n # Suppress warnings since they just mean we didn't find the coordinate\n warnings.simplefilter(\"ignore\")\n try:\n x, y = self.to_pixel(wcs, **kwargs)\n except Exception:\n return False\n\n return (x < xmax) & (x > 0) & (y < ymax) & (y > 0)\n\n def radial_velocity_correction(self, kind='barycentric', obstime=None,\n location=None):\n \"\"\"\n Compute the correction required to convert a radial velocity at a given\n time and place on the Earth's Surface to a barycentric or heliocentric\n velocity.\n\n Parameters\n ----------\n kind : str\n The kind of velocity correction. Must be 'barycentric' or\n 'heliocentric'.\n obstime : `~astropy.time.Time` or None, optional\n The time at which to compute the correction. If `None`, the\n ``obstime`` frame attribute on the `SkyCoord` will be used.\n location : `~astropy.coordinates.EarthLocation` or None, optional\n The observer location at which to compute the correction. If\n `None`, the ``location`` frame attribute on the passed-in\n ``obstime`` will be used, and if that is None, the ``location``\n frame attribute on the `SkyCoord` will be used.\n\n Raises\n ------\n ValueError\n If either ``obstime`` or ``location`` are passed in (not ``None``)\n when the frame attribute is already set on this `SkyCoord`.\n TypeError\n If ``obstime`` or ``location`` aren't provided, either as arguments\n or as frame attributes.\n\n Returns\n -------\n vcorr : `~astropy.units.Quantity` with velocity units\n The correction with a positive sign. I.e., *add* this\n to an observed radial velocity to get the barycentric (or\n heliocentric) velocity. If m/s precision or better is needed,\n see the notes below.\n\n Notes\n -----\n The barycentric correction is calculated to higher precision than the\n heliocentric correction and includes additional physics (e.g time dilation).\n Use barycentric corrections if m/s precision is required.\n\n The algorithm here is sufficient to perform corrections at the mm/s level, but\n care is needed in application. The barycentric correction returned uses the optical\n approximation v = z * c. Strictly speaking, the barycentric correction is\n multiplicative and should be applied as::\n\n >>> from astropy.time import Time\n >>> from astropy.coordinates import SkyCoord, EarthLocation\n >>> from astropy.constants import c\n >>> t = Time(56370.5, format='mjd', scale='utc')\n >>> loc = EarthLocation('149d33m00.5s','-30d18m46.385s',236.87*u.m)\n >>> sc = SkyCoord(1*u.deg, 2*u.deg)\n >>> vcorr = sc.radial_velocity_correction(kind='barycentric', obstime=t, location=loc) # doctest: +REMOTE_DATA\n >>> rv = rv + vcorr + rv * vcorr / c # doctest: +SKIP\n\n Also note that this method returns the correction velocity in the so-called\n *optical convention*::\n\n >>> vcorr = zb * c # doctest: +SKIP\n\n where ``zb`` is the barycentric correction redshift as defined in section 3\n of Wright & Eastman (2014). The application formula given above follows from their\n equation (11) under assumption that the radial velocity ``rv`` has also been defined\n using the same optical convention. Note, this can be regarded as a matter of\n velocity definition and does not by itself imply any loss of accuracy, provided\n sufficient care has been taken during interpretation of the results. If you need\n the barycentric correction expressed as the full relativistic velocity (e.g., to provide\n it as the input to another software which performs the application), the\n following recipe can be used::\n\n >>> zb = vcorr / c # doctest: +REMOTE_DATA\n >>> zb_plus_one_squared = (zb + 1) ** 2 # doctest: +REMOTE_DATA\n >>> vcorr_rel = c * (zb_plus_one_squared - 1) / (zb_plus_one_squared + 1) # doctest: +REMOTE_DATA\n\n or alternatively using just equivalencies::\n\n >>> vcorr_rel = vcorr.to(u.Hz, u.doppler_optical(1*u.Hz)).to(vcorr.unit, u.doppler_relativistic(1*u.Hz)) # doctest: +REMOTE_DATA\n\n See also `~astropy.units.equivalencies.doppler_optical`,\n `~astropy.units.equivalencies.doppler_radio`, and\n `~astropy.units.equivalencies.doppler_relativistic` for more information on\n the velocity conventions.\n\n The default is for this method to use the builtin ephemeris for\n computing the sun and earth location. Other ephemerides can be chosen\n by setting the `~astropy.coordinates.solar_system_ephemeris` variable,\n either directly or via ``with`` statement. For example, to use the JPL\n ephemeris, do::\n\n >>> from astropy.coordinates import solar_system_ephemeris\n >>> sc = SkyCoord(1*u.deg, 2*u.deg)\n >>> with solar_system_ephemeris.set('jpl'): # doctest: +REMOTE_DATA\n ... rv += sc.radial_velocity_correction(obstime=t, location=loc) # doctest: +SKIP\n\n \"\"\"\n # has to be here to prevent circular imports\n from .solar_system import get_body_barycentric_posvel\n\n # location validation\n timeloc = getattr(obstime, 'location', None)\n if location is None:\n if self.location is not None:\n location = self.location\n if timeloc is not None:\n raise ValueError('`location` cannot be in both the '\n 'passed-in `obstime` and this `SkyCoord` '\n 'because it is ambiguous which is meant '\n 'for the radial_velocity_correction.')\n elif timeloc is not None:\n location = timeloc\n else:\n raise TypeError('Must provide a `location` to '\n 'radial_velocity_correction, either as a '\n 'SkyCoord frame attribute, as an attribute on '\n 'the passed in `obstime`, or in the method '\n 'call.')\n\n elif self.location is not None or timeloc is not None:\n raise ValueError('Cannot compute radial velocity correction if '\n '`location` argument is passed in and there is '\n 'also a `location` attribute on this SkyCoord or '\n 'the passed-in `obstime`.')\n\n # obstime validation\n coo_at_rv_obstime = self # assume we need no space motion for now\n if obstime is None:\n obstime = self.obstime\n if obstime is None:\n raise TypeError('Must provide an `obstime` to '\n 'radial_velocity_correction, either as a '\n 'SkyCoord frame attribute or in the method '\n 'call.')\n elif self.obstime is not None and self.frame.data.differentials:\n # we do need space motion after all\n coo_at_rv_obstime = self.apply_space_motion(obstime)\n elif self.obstime is None:\n # warn the user if the object has differentials set\n if 's' in self.data.differentials:\n warnings.warn(\n \"SkyCoord has space motion, and therefore the specified \"\n \"position of the SkyCoord may not be the same as \"\n \"the `obstime` for the radial velocity measurement. \"\n \"This may affect the rv correction at the order of km/s\"\n \"for very high proper motions sources. If you wish to \"\n \"apply space motion of the SkyCoord to correct for this\"\n \"the `obstime` attribute of the SkyCoord must be set\",\n AstropyUserWarning\n )\n\n pos_earth, v_earth = get_body_barycentric_posvel('earth', obstime)\n if kind == 'barycentric':\n v_origin_to_earth = v_earth\n elif kind == 'heliocentric':\n v_sun = get_body_barycentric_posvel('sun', obstime)[1]\n v_origin_to_earth = v_earth - v_sun\n else:\n raise ValueError(\"`kind` argument to radial_velocity_correction must \"\n \"be 'barycentric' or 'heliocentric', but got \"\n \"'{}'\".format(kind))\n\n gcrs_p, gcrs_v = location.get_gcrs_posvel(obstime)\n # transforming to GCRS is not the correct thing to do here, since we don't want to\n # include aberration (or light deflection)? Instead, only apply parallax if necessary\n icrs_cart = coo_at_rv_obstime.icrs.cartesian\n icrs_cart_novel = icrs_cart.without_differentials()\n if self.data.__class__ is UnitSphericalRepresentation:\n targcart = icrs_cart_novel\n else:\n # skycoord has distances so apply parallax\n obs_icrs_cart = pos_earth + gcrs_p\n targcart = icrs_cart_novel - obs_icrs_cart\n targcart /= targcart.norm()\n\n if kind == 'barycentric':\n beta_obs = (v_origin_to_earth + gcrs_v) / speed_of_light\n gamma_obs = 1 / np.sqrt(1 - beta_obs.norm()**2)\n gr = location.gravitational_redshift(obstime)\n # barycentric redshift according to eq 28 in Wright & Eastmann (2014),\n # neglecting Shapiro delay and effects of the star's own motion\n zb = gamma_obs * (1 + beta_obs.dot(targcart)) / (1 + gr/speed_of_light)\n # try and get terms corresponding to stellar motion.\n if icrs_cart.differentials:\n try:\n ro = self.icrs.cartesian\n beta_star = ro.differentials['s'].to_cartesian() / speed_of_light\n # ICRS unit vector at coordinate epoch\n ro = ro.without_differentials()\n ro /= ro.norm()\n zb *= (1 + beta_star.dot(ro)) / (1 + beta_star.dot(targcart))\n except u.UnitConversionError:\n warnings.warn(\"SkyCoord contains some velocity information, but not enough to \"\n \"calculate the full space motion of the source, and so this has \"\n \"been ignored for the purposes of calculating the radial velocity \"\n \"correction. This can lead to errors on the order of metres/second.\",\n AstropyUserWarning)\n\n zb = zb - 1\n return zb * speed_of_light\n else:\n # do a simpler correction ignoring time dilation and gravitational redshift\n # this is adequate since Heliocentric corrections shouldn't be used if\n # cm/s precision is required.\n return targcart.dot(v_origin_to_earth + gcrs_v)\n\n # Table interactions\n @classmethod\n def guess_from_table(cls, table, **coord_kwargs):\n r\"\"\"\n A convenience method to create and return a new `SkyCoord` from the data\n in an astropy Table.\n\n This method matches table columns that start with the case-insensitive\n names of the the components of the requested frames, if they are also\n followed by a non-alphanumeric character. It will also match columns\n that *end* with the component name if a non-alphanumeric character is\n *before* it.\n\n For example, the first rule means columns with names like\n ``'RA[J2000]'`` or ``'ra'`` will be interpreted as ``ra`` attributes for\n `~astropy.coordinates.ICRS` frames, but ``'RAJ2000'`` or ``'radius'``\n are *not*. Similarly, the second rule applied to the\n `~astropy.coordinates.Galactic` frame means that a column named\n ``'gal_l'`` will be used as the the ``l`` component, but ``gall`` or\n ``'fill'`` will not.\n\n The definition of alphanumeric here is based on Unicode's definition\n of alphanumeric, except without ``_`` (which is normally considered\n alphanumeric). So for ASCII, this means the non-alphanumeric characters\n are ``<space>_!\"#$%&'()*+,-./\\:;<=>?@[]^`{|}~``).\n\n Parameters\n ----------\n table : astropy.Table\n The table to load data from.\n coord_kwargs\n Any additional keyword arguments are passed directly to this class's\n constructor.\n\n Returns\n -------\n newsc : same as this class\n The new `SkyCoord` (or subclass) object.\n \"\"\"\n _frame_cls, _frame_kwargs = _get_frame_without_data([], coord_kwargs)\n frame = _frame_cls(**_frame_kwargs)\n coord_kwargs['frame'] = coord_kwargs.get('frame', frame)\n\n comp_kwargs = {}\n for comp_name in frame.representation_component_names:\n # this matches things like 'ra[...]'' but *not* 'rad'.\n # note that the \"_\" must be in there explicitly, because\n # \"alphanumeric\" usually includes underscores.\n starts_with_comp = comp_name + r'(\\W|\\b|_)'\n # this part matches stuff like 'center_ra', but *not*\n # 'aura'\n ends_with_comp = r'.*(\\W|\\b|_)' + comp_name + r'\\b'\n # the final regex ORs together the two patterns\n rex = re.compile('(' + starts_with_comp + ')|(' + ends_with_comp + ')',\n re.IGNORECASE | re.UNICODE)\n\n for col_name in table.colnames:\n if rex.match(col_name):\n if comp_name in comp_kwargs:\n oldname = comp_kwargs[comp_name].name\n msg = ('Found at least two matches for component \"{0}\"'\n ': \"{1}\" and \"{2}\". Cannot continue with this '\n 'ambiguity.')\n raise ValueError(msg.format(comp_name, oldname, col_name))\n comp_kwargs[comp_name] = table[col_name]\n\n for k, v in comp_kwargs.items():\n if k in coord_kwargs:\n raise ValueError('Found column \"{}\" in table, but it was '\n 'already provided as \"{}\" keyword to '\n 'guess_from_table function.'.format(v.name, k))\n else:\n coord_kwargs[k] = v\n\n return cls(**coord_kwargs)\n\n # Name resolve\n @classmethod\n def from_name(cls, name, frame='icrs', parse=False, cache=True):\n \"\"\"\n Given a name, query the CDS name resolver to attempt to retrieve\n coordinate information for that object. The search database, sesame\n url, and query timeout can be set through configuration items in\n ``astropy.coordinates.name_resolve`` -- see docstring for\n `~astropy.coordinates.get_icrs_coordinates` for more\n information.\n\n Parameters\n ----------\n name : str\n The name of the object to get coordinates for, e.g. ``'M42'``.\n frame : str or `BaseCoordinateFrame` class or instance\n The frame to transform the object to.\n parse: bool\n Whether to attempt extracting the coordinates from the name by\n parsing with a regex. For objects catalog names that have\n J-coordinates embedded in their names, e.g.,\n 'CRTS SSS100805 J194428-420209', this may be much faster than a\n Sesame query for the same object name. The coordinates extracted\n in this way may differ from the database coordinates by a few\n deci-arcseconds, so only use this option if you do not need\n sub-arcsecond accuracy for coordinates.\n cache : bool, optional\n Determines whether to cache the results or not. To update or\n overwrite an existing value, pass ``cache='update'``.\n\n Returns\n -------\n coord : SkyCoord\n Instance of the SkyCoord class.\n \"\"\"\n\n from .name_resolve import get_icrs_coordinates\n\n icrs_coord = get_icrs_coordinates(name, parse, cache=cache)\n icrs_sky_coord = cls(icrs_coord)\n if frame in ('icrs', icrs_coord.__class__):\n return icrs_sky_coord\n else:\n return icrs_sky_coord.transform_to(frame)\n", "# Licensed under a 3-clause BSD style license - see PYFITS.rst\n\nimport gzip\nimport io\nimport mmap\nimport errno\nimport os\nimport pathlib\nimport urllib.request\nimport warnings\nimport zipfile\nfrom unittest.mock import patch\n\nimport pytest\nimport numpy as np\n\nfrom . import FitsTestCase\n\nfrom astropy.io.fits.convenience import _getext\nfrom astropy.io.fits.diff import FITSDiff\nfrom astropy.io.fits.file import _File, GZIP_MAGIC\n\nfrom astropy.io import fits\nfrom astropy.tests.helper import raises, catch_warnings, ignore_warnings\nfrom astropy.utils.data import conf\nfrom astropy.utils.exceptions import AstropyUserWarning\nfrom astropy.utils import data\n\n# NOTE: Python can be built without bz2.\ntry:\n import bz2\nexcept ImportError:\n HAS_BZ2 = False\nelse:\n HAS_BZ2 = True\n\n\nclass TestCore(FitsTestCase):\n\n @raises(OSError)\n def test_missing_file(self):\n fits.open(self.temp('does-not-exist.fits'))\n\n def test_naxisj_check(self):\n with fits.open(self.data('o4sp040b0_raw.fits')) as hdulist:\n hdulist[1].header['NAXIS3'] = 500\n\n assert 'NAXIS3' in hdulist[1].header\n hdulist.verify('silentfix')\n assert 'NAXIS3' not in hdulist[1].header\n\n def test_byteswap(self):\n p = fits.PrimaryHDU()\n l = fits.HDUList()\n\n n = np.zeros(3, dtype='i2')\n n[0] = 1\n n[1] = 60000\n n[2] = 2\n\n c = fits.Column(name='foo', format='i2', bscale=1, bzero=32768,\n array=n)\n t = fits.BinTableHDU.from_columns([c])\n\n l.append(p)\n l.append(t)\n\n l.writeto(self.temp('test.fits'), overwrite=True)\n\n with fits.open(self.temp('test.fits')) as p:\n assert p[1].data[1]['foo'] == 60000.0\n\n def test_fits_file_path_object(self):\n \"\"\"\n Testing when fits file is passed as pathlib.Path object #4412.\n \"\"\"\n fpath = pathlib.Path(self.data('tdim.fits'))\n with fits.open(fpath) as hdulist:\n assert hdulist[0].filebytes() == 2880\n assert hdulist[1].filebytes() == 5760\n\n with fits.open(self.data('tdim.fits')) as hdulist2:\n assert FITSDiff(hdulist2, hdulist).identical is True\n\n def test_fits_file_bytes_object(self):\n \"\"\"\n Testing when fits file is passed as bytes.\n \"\"\"\n with fits.open(self.data('tdim.fits').encode()) as hdulist:\n assert hdulist[0].filebytes() == 2880\n assert hdulist[1].filebytes() == 5760\n\n with fits.open(self.data('tdim.fits')) as hdulist2:\n assert FITSDiff(hdulist2, hdulist).identical is True\n\n def test_add_del_columns(self):\n p = fits.ColDefs([])\n p.add_col(fits.Column(name='FOO', format='3J'))\n p.add_col(fits.Column(name='BAR', format='1I'))\n assert p.names == ['FOO', 'BAR']\n p.del_col('FOO')\n assert p.names == ['BAR']\n\n def test_add_del_columns2(self):\n hdulist = fits.open(self.data('tb.fits'))\n table = hdulist[1]\n assert table.data.dtype.names == ('c1', 'c2', 'c3', 'c4')\n assert table.columns.names == ['c1', 'c2', 'c3', 'c4']\n table.columns.del_col('c1')\n assert table.data.dtype.names == ('c2', 'c3', 'c4')\n assert table.columns.names == ['c2', 'c3', 'c4']\n\n table.columns.del_col('c3')\n assert table.data.dtype.names == ('c2', 'c4')\n assert table.columns.names == ['c2', 'c4']\n\n table.columns.add_col(fits.Column('foo', '3J'))\n assert table.data.dtype.names == ('c2', 'c4', 'foo')\n assert table.columns.names == ['c2', 'c4', 'foo']\n\n hdulist.writeto(self.temp('test.fits'), overwrite=True)\n with ignore_warnings():\n # TODO: The warning raised by this test is actually indication of a\n # bug and should *not* be ignored. But as it is a known issue we\n # hide it for now. See\n # https://github.com/spacetelescope/PyFITS/issues/44\n with fits.open(self.temp('test.fits')) as hdulist:\n table = hdulist[1]\n assert table.data.dtype.names == ('c2', 'c4', 'foo')\n assert table.columns.names == ['c2', 'c4', 'foo']\n\n def test_update_header_card(self):\n \"\"\"A very basic test for the Header.update method--I'd like to add a\n few more cases to this at some point.\n \"\"\"\n\n header = fits.Header()\n comment = 'number of bits per data pixel'\n header['BITPIX'] = (16, comment)\n assert 'BITPIX' in header\n assert header['BITPIX'] == 16\n assert header.comments['BITPIX'] == comment\n\n header.update(BITPIX=32)\n assert header['BITPIX'] == 32\n assert header.comments['BITPIX'] == ''\n\n def test_set_card_value(self):\n \"\"\"Similar to test_update_header_card(), but tests the the\n `header['FOO'] = 'bar'` method of updating card values.\n \"\"\"\n\n header = fits.Header()\n comment = 'number of bits per data pixel'\n card = fits.Card.fromstring(f'BITPIX = 32 / {comment}')\n header.append(card)\n\n header['BITPIX'] = 32\n\n assert 'BITPIX' in header\n assert header['BITPIX'] == 32\n assert header.cards[0].keyword == 'BITPIX'\n assert header.cards[0].value == 32\n assert header.cards[0].comment == comment\n\n def test_uint(self):\n filename = self.data('o4sp040b0_raw.fits')\n with fits.open(filename, uint=False) as hdulist_f:\n with fits.open(filename, uint=True) as hdulist_i:\n assert hdulist_f[1].data.dtype == np.float32\n assert hdulist_i[1].data.dtype == np.uint16\n assert np.all(hdulist_f[1].data == hdulist_i[1].data)\n\n def test_fix_missing_card_append(self):\n hdu = fits.ImageHDU()\n errs = hdu.req_cards('TESTKW', None, None, 'foo', 'silentfix', [])\n assert len(errs) == 1\n assert 'TESTKW' in hdu.header\n assert hdu.header['TESTKW'] == 'foo'\n assert hdu.header.cards[-1].keyword == 'TESTKW'\n\n def test_fix_invalid_keyword_value(self):\n hdu = fits.ImageHDU()\n hdu.header['TESTKW'] = 'foo'\n errs = hdu.req_cards('TESTKW', None,\n lambda v: v == 'foo', 'foo', 'ignore', [])\n assert len(errs) == 0\n\n # Now try a test that will fail, and ensure that an error will be\n # raised in 'exception' mode\n errs = hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar',\n 'exception', [])\n assert len(errs) == 1\n assert errs[0][1] == \"'TESTKW' card has invalid value 'foo'.\"\n\n # See if fixing will work\n hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar', 'silentfix',\n [])\n assert hdu.header['TESTKW'] == 'bar'\n\n @raises(fits.VerifyError)\n def test_unfixable_missing_card(self):\n class TestHDU(fits.hdu.base.NonstandardExtHDU):\n def _verify(self, option='warn'):\n errs = super()._verify(option)\n hdu.req_cards('TESTKW', None, None, None, 'fix', errs)\n return errs\n\n @classmethod\n def match_header(cls, header):\n # Since creating this HDU class adds it to the registry we\n # don't want the file reader to possibly think any actual\n # HDU from a file should be handled by this class\n return False\n\n hdu = TestHDU(header=fits.Header())\n hdu.verify('fix')\n\n @raises(fits.VerifyError)\n def test_exception_on_verification_error(self):\n hdu = fits.ImageHDU()\n del hdu.header['XTENSION']\n hdu.verify('exception')\n\n def test_ignore_verification_error(self):\n hdu = fits.ImageHDU()\n # The default here would be to issue a warning; ensure that no warnings\n # or exceptions are raised\n with catch_warnings():\n warnings.simplefilter('error')\n del hdu.header['NAXIS']\n try:\n hdu.verify('ignore')\n except Exception as exc:\n self.fail('An exception occurred when the verification error '\n 'should have been ignored: {}'.format(exc))\n # Make sure the error wasn't fixed either, silently or otherwise\n assert 'NAXIS' not in hdu.header\n\n @raises(ValueError)\n def test_unrecognized_verify_option(self):\n hdu = fits.ImageHDU()\n hdu.verify('foobarbaz')\n\n def test_errlist_basic(self):\n # Just some tests to make sure that _ErrList is setup correctly.\n # No arguments\n error_list = fits.verify._ErrList()\n assert error_list == []\n # Some contents - this is not actually working, it just makes sure they\n # are kept.\n error_list = fits.verify._ErrList([1, 2, 3])\n assert error_list == [1, 2, 3]\n\n def test_combined_verify_options(self):\n \"\"\"\n Test verify options like fix+ignore.\n \"\"\"\n\n def make_invalid_hdu():\n hdu = fits.ImageHDU()\n # Add one keyword to the header that contains a fixable defect, and one\n # with an unfixable defect\n c1 = fits.Card.fromstring(\"test = ' test'\")\n c2 = fits.Card.fromstring(\"P.I. = ' Hubble'\")\n hdu.header.append(c1)\n hdu.header.append(c2)\n return hdu\n\n # silentfix+ignore should be completely silent\n hdu = make_invalid_hdu()\n with catch_warnings():\n warnings.simplefilter('error')\n try:\n hdu.verify('silentfix+ignore')\n except Exception as exc:\n self.fail('An exception occurred when the verification error '\n 'should have been ignored: {}'.format(exc))\n\n # silentfix+warn should be quiet about the fixed HDU and only warn\n # about the unfixable one\n hdu = make_invalid_hdu()\n with catch_warnings() as w:\n hdu.verify('silentfix+warn')\n assert len(w) == 4\n assert 'Illegal keyword name' in str(w[2].message)\n\n # silentfix+exception should only mention the unfixable error in the\n # exception\n hdu = make_invalid_hdu()\n with pytest.raises(fits.VerifyError, match=r'Illegal keyword name') as excinfo:\n hdu.verify('silentfix+exception')\n assert 'not upper case' not in str(excinfo.value)\n\n # fix+ignore is not too useful, but it should warn about the fixed\n # problems while saying nothing about the unfixable problems\n hdu = make_invalid_hdu()\n with catch_warnings() as w:\n hdu.verify('fix+ignore')\n assert len(w) == 4\n assert 'not upper case' in str(w[2].message)\n\n # fix+warn\n hdu = make_invalid_hdu()\n with catch_warnings() as w:\n hdu.verify('fix+warn')\n assert len(w) == 6\n assert 'not upper case' in str(w[2].message)\n assert 'Illegal keyword name' in str(w[4].message)\n\n # fix+exception\n hdu = make_invalid_hdu()\n with pytest.raises(fits.VerifyError, match=r'Illegal keyword name') as excinfo:\n hdu.verify('fix+exception')\n assert 'not upper case' in str(excinfo.value)\n\n def test_getext(self):\n \"\"\"\n Test the various different ways of specifying an extension header in\n the convenience functions.\n \"\"\"\n filename = self.data('test0.fits')\n\n hl, ext = _getext(filename, 'readonly', 1)\n assert ext == 1\n hl.close()\n\n pytest.raises(ValueError, _getext, filename, 'readonly',\n 1, 2)\n pytest.raises(ValueError, _getext, filename, 'readonly',\n (1, 2))\n pytest.raises(ValueError, _getext, filename, 'readonly',\n 'sci', 'sci')\n pytest.raises(TypeError, _getext, filename, 'readonly',\n 1, 2, 3)\n\n hl, ext = _getext(filename, 'readonly', ext=1)\n assert ext == 1\n hl.close()\n\n hl, ext = _getext(filename, 'readonly', ext=('sci', 2))\n assert ext == ('sci', 2)\n hl.close()\n\n pytest.raises(TypeError, _getext, filename, 'readonly',\n 1, ext=('sci', 2), extver=3)\n pytest.raises(TypeError, _getext, filename, 'readonly',\n ext=('sci', 2), extver=3)\n\n hl, ext = _getext(filename, 'readonly', 'sci')\n assert ext == ('sci', 1)\n hl.close()\n\n hl, ext = _getext(filename, 'readonly', 'sci', 1)\n assert ext == ('sci', 1)\n hl.close()\n\n hl, ext = _getext(filename, 'readonly', ('sci', 1))\n assert ext == ('sci', 1)\n hl.close()\n\n hl, ext = _getext(filename, 'readonly', 'sci',\n extver=1, do_not_scale_image_data=True)\n assert ext == ('sci', 1)\n hl.close()\n\n pytest.raises(TypeError, _getext, filename, 'readonly',\n 'sci', ext=1)\n pytest.raises(TypeError, _getext, filename, 'readonly',\n 'sci', 1, extver=2)\n\n hl, ext = _getext(filename, 'readonly', extname='sci')\n assert ext == ('sci', 1)\n hl.close()\n\n hl, ext = _getext(filename, 'readonly', extname='sci',\n extver=1)\n assert ext == ('sci', 1)\n hl.close()\n\n pytest.raises(TypeError, _getext, filename, 'readonly',\n extver=1)\n\n def test_extension_name_case_sensitive(self):\n \"\"\"\n Tests that setting fits.conf.extension_name_case_sensitive at\n runtime works.\n \"\"\"\n\n hdu = fits.ImageHDU()\n hdu.name = 'sCi'\n assert hdu.name == 'SCI'\n assert hdu.header['EXTNAME'] == 'SCI'\n\n with fits.conf.set_temp('extension_name_case_sensitive', True):\n hdu = fits.ImageHDU()\n hdu.name = 'sCi'\n assert hdu.name == 'sCi'\n assert hdu.header['EXTNAME'] == 'sCi'\n\n hdu.name = 'sCi'\n assert hdu.name == 'SCI'\n assert hdu.header['EXTNAME'] == 'SCI'\n\n def test_hdu_fromstring(self):\n \"\"\"\n Tests creating a fully-formed HDU object from a string containing the\n bytes of the HDU.\n \"\"\"\n infile = self.data('test0.fits')\n outfile = self.temp('test.fits')\n\n with open(infile, 'rb') as fin:\n dat = fin.read()\n\n offset = 0\n with fits.open(infile) as hdul:\n hdulen = hdul[0]._data_offset + hdul[0]._data_size\n hdu = fits.PrimaryHDU.fromstring(dat[:hdulen])\n assert isinstance(hdu, fits.PrimaryHDU)\n assert hdul[0].header == hdu.header\n assert hdu.data is None\n\n hdu.header['TEST'] = 'TEST'\n hdu.writeto(outfile)\n with fits.open(outfile) as hdul:\n assert isinstance(hdu, fits.PrimaryHDU)\n assert hdul[0].header[:-1] == hdu.header[:-1]\n assert hdul[0].header['TEST'] == 'TEST'\n assert hdu.data is None\n\n with fits.open(infile)as hdul:\n for ext_hdu in hdul[1:]:\n offset += hdulen\n hdulen = len(str(ext_hdu.header)) + ext_hdu._data_size\n hdu = fits.ImageHDU.fromstring(dat[offset:offset + hdulen])\n assert isinstance(hdu, fits.ImageHDU)\n assert ext_hdu.header == hdu.header\n assert (ext_hdu.data == hdu.data).all()\n\n def test_nonstandard_hdu(self):\n \"\"\"\n Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/157\n\n Tests that \"Nonstandard\" HDUs with SIMPLE = F are read and written\n without prepending a superfluous and unwanted standard primary HDU.\n \"\"\"\n\n data = np.arange(100, dtype=np.uint8)\n hdu = fits.PrimaryHDU(data=data)\n hdu.header['SIMPLE'] = False\n hdu.writeto(self.temp('test.fits'))\n\n info = [(0, '', 1, 'NonstandardHDU', 5, (), '', '')]\n with fits.open(self.temp('test.fits')) as hdul:\n assert hdul.info(output=False) == info\n # NonstandardHDUs just treat the data as an unspecified array of\n # bytes. The first 100 bytes should match the original data we\n # passed in...the rest should be zeros padding out the rest of the\n # FITS block\n assert (hdul[0].data[:100] == data).all()\n assert (hdul[0].data[100:] == 0).all()\n\n def test_extname(self):\n \"\"\"Test getting/setting the EXTNAME of an HDU.\"\"\"\n\n h1 = fits.PrimaryHDU()\n assert h1.name == 'PRIMARY'\n # Normally a PRIMARY HDU should not have an EXTNAME, though it should\n # have a default .name attribute\n assert 'EXTNAME' not in h1.header\n\n # The current version of the FITS standard does allow PRIMARY HDUs to\n # have an EXTNAME, however.\n h1.name = 'NOTREAL'\n assert h1.name == 'NOTREAL'\n assert h1.header.get('EXTNAME') == 'NOTREAL'\n\n # Updating the EXTNAME in the header should update the .name\n h1.header['EXTNAME'] = 'TOOREAL'\n assert h1.name == 'TOOREAL'\n\n # If we delete an EXTNAME keyword from a PRIMARY HDU it should go back\n # to the default\n del h1.header['EXTNAME']\n assert h1.name == 'PRIMARY'\n\n # For extension HDUs the situation is a bit simpler:\n h2 = fits.ImageHDU()\n assert h2.name == ''\n assert 'EXTNAME' not in h2.header\n h2.name = 'HELLO'\n assert h2.name == 'HELLO'\n assert h2.header.get('EXTNAME') == 'HELLO'\n h2.header['EXTNAME'] = 'GOODBYE'\n assert h2.name == 'GOODBYE'\n\n def test_extver_extlevel(self):\n \"\"\"Test getting/setting the EXTVER and EXTLEVEL of and HDU.\"\"\"\n\n # EXTVER and EXTNAME work exactly the same; their semantics are, for\n # now, to be inferred by the user. Although they should never be less\n # than 1, the standard does not explicitly forbid any value so long as\n # it's an integer\n h1 = fits.PrimaryHDU()\n assert h1.ver == 1\n assert h1.level == 1\n assert 'EXTVER' not in h1.header\n assert 'EXTLEVEL' not in h1.header\n\n h1.ver = 2\n assert h1.header.get('EXTVER') == 2\n h1.header['EXTVER'] = 3\n assert h1.ver == 3\n del h1.header['EXTVER']\n h1.ver == 1\n\n h1.level = 2\n assert h1.header.get('EXTLEVEL') == 2\n h1.header['EXTLEVEL'] = 3\n assert h1.level == 3\n del h1.header['EXTLEVEL']\n assert h1.level == 1\n\n pytest.raises(TypeError, setattr, h1, 'ver', 'FOO')\n pytest.raises(TypeError, setattr, h1, 'level', 'BAR')\n\n def test_consecutive_writeto(self):\n \"\"\"\n Regression test for an issue where calling writeto twice on the same\n HDUList could write a corrupted file.\n\n https://github.com/spacetelescope/PyFITS/issues/40 is actually a\n particular instance of this problem, though isn't unique to sys.stdout.\n \"\"\"\n\n with fits.open(self.data('test0.fits')) as hdul1:\n # Add a bunch of header keywords so that the data will be forced to\n # new offsets within the file:\n for idx in range(40):\n hdul1[1].header[f'TEST{idx}'] = 'test'\n\n hdul1.writeto(self.temp('test1.fits'))\n hdul1.writeto(self.temp('test2.fits'))\n\n # Open a second handle to the original file and compare it to hdul1\n # (We only compare part of the one header that was modified)\n # Compare also with the second writeto output\n with fits.open(self.data('test0.fits')) as hdul2:\n with fits.open(self.temp('test2.fits')) as hdul3:\n for hdul in (hdul1, hdul3):\n for idx, hdus in enumerate(zip(hdul2, hdul)):\n hdu2, hdu = hdus\n if idx != 1:\n assert hdu.header == hdu2.header\n else:\n assert (hdu2.header ==\n hdu.header[:len(hdu2.header)])\n assert np.all(hdu.data == hdu2.data)\n\n\nclass TestConvenienceFunctions(FitsTestCase):\n def test_writeto(self):\n \"\"\"\n Simple test for writing a trivial header and some data to a file\n with the `writeto()` convenience function.\n \"\"\"\n filename = self.temp('array.fits')\n data = np.zeros((100, 100))\n header = fits.Header()\n fits.writeto(filename, data, header=header, overwrite=True)\n with fits.open(filename) as hdul:\n assert len(hdul) == 1\n assert (data == hdul[0].data).all()\n\n def test_writeto_2(self):\n \"\"\"\n Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/107\n\n Test of `writeto()` with a trivial header containing a single keyword.\n \"\"\"\n filename = self.temp('array.fits')\n data = np.zeros((100, 100))\n header = fits.Header()\n header.set('CRPIX1', 1.)\n fits.writeto(filename, data, header=header,\n overwrite=True, output_verify='silentfix')\n with fits.open(filename) as hdul:\n assert len(hdul) == 1\n assert (data == hdul[0].data).all()\n assert 'CRPIX1' in hdul[0].header\n assert hdul[0].header['CRPIX1'] == 1.0\n\n\nclass TestFileFunctions(FitsTestCase):\n \"\"\"\n Tests various basic I/O operations, specifically in the\n astropy.io.fits.file._File class.\n \"\"\"\n\n def test_open_nonexistent(self):\n \"\"\"Test that trying to open a non-existent file results in an\n OSError (and not some other arbitrary exception).\n \"\"\"\n\n with pytest.raises(OSError, match=r'No such file or directory'):\n fits.open(self.temp('foobar.fits'))\n\n # But opening in ostream or append mode should be okay, since they\n # allow writing new files\n for mode in ('ostream', 'append'):\n with fits.open(self.temp('foobar.fits'), mode=mode) as _:\n pass\n\n assert os.path.exists(self.temp('foobar.fits'))\n os.remove(self.temp('foobar.fits'))\n\n def test_open_file_handle(self):\n # Make sure we can open a FITS file from an open file handle\n with open(self.data('test0.fits'), 'rb') as handle:\n with fits.open(handle) as _:\n pass\n\n with open(self.temp('temp.fits'), 'wb') as handle:\n with fits.open(handle, mode='ostream') as _:\n pass\n\n # Opening without explicitly specifying binary mode should fail\n with pytest.raises(ValueError):\n with open(self.data('test0.fits')) as handle:\n with fits.open(handle) as _:\n pass\n\n # All of these read modes should fail\n for mode in ['r', 'rt']:\n with pytest.raises(ValueError):\n with open(self.data('test0.fits'), mode=mode) as handle:\n with fits.open(handle) as _:\n pass\n\n # These update or write modes should fail as well\n for mode in ['w', 'wt', 'w+', 'wt+', 'r+', 'rt+',\n 'a', 'at', 'a+', 'at+']:\n with pytest.raises(ValueError):\n with open(self.temp('temp.fits'), mode=mode) as handle:\n with fits.open(handle) as _:\n pass\n\n def test_fits_file_handle_mode_combo(self):\n # This should work fine since no mode is given\n with open(self.data('test0.fits'), 'rb') as handle:\n with fits.open(handle) as _:\n pass\n\n # This should work fine since the modes are compatible\n with open(self.data('test0.fits'), 'rb') as handle:\n with fits.open(handle, mode='readonly') as _:\n pass\n\n # This should not work since the modes conflict\n with pytest.raises(ValueError):\n with open(self.data('test0.fits'), 'rb') as handle:\n with fits.open(handle, mode='ostream') as _:\n pass\n\n def test_open_from_url(self):\n file_url = 'file:///' + self.data('test0.fits').lstrip('/')\n with urllib.request.urlopen(file_url) as urlobj:\n with fits.open(urlobj) as _:\n pass\n\n # It will not be possible to write to a file that is from a URL object\n for mode in ('ostream', 'append', 'update'):\n with pytest.raises(ValueError):\n with urllib.request.urlopen(file_url) as urlobj:\n with fits.open(urlobj, mode=mode) as _:\n pass\n\n @pytest.mark.remote_data(source='astropy')\n def test_open_from_remote_url(self):\n for dataurl in (conf.dataurl, conf.dataurl_mirror):\n remote_url = '{}/{}'.format(dataurl, 'allsky/allsky_rosat.fits')\n try:\n with urllib.request.urlopen(remote_url) as urlobj:\n with fits.open(urlobj) as fits_handle:\n assert len(fits_handle) == 1\n\n for mode in ('ostream', 'append', 'update'):\n with pytest.raises(ValueError):\n with urllib.request.urlopen(remote_url) as urlobj:\n with fits.open(urlobj, mode=mode) as fits_handle:\n assert len(fits_handle) == 1\n except (urllib.error.HTTPError, urllib.error.URLError):\n continue\n else:\n break\n else:\n raise Exception(\"Could not download file\")\n\n def test_open_gzipped(self):\n gzip_file = self._make_gzip_file()\n with ignore_warnings():\n with fits.open(gzip_file) as fits_handle:\n assert fits_handle._file.compression == 'gzip'\n assert len(fits_handle) == 5\n with fits.open(gzip.GzipFile(gzip_file)) as fits_handle:\n assert fits_handle._file.compression == 'gzip'\n assert len(fits_handle) == 5\n\n def test_open_gzipped_from_handle(self):\n with open(self._make_gzip_file(), 'rb') as handle:\n with fits.open(handle) as fits_handle:\n assert fits_handle._file.compression == 'gzip'\n\n def test_detect_gzipped(self):\n \"\"\"Test detection of a gzip file when the extension is not .gz.\"\"\"\n with ignore_warnings():\n with fits.open(self._make_gzip_file('test0.fz')) as fits_handle:\n assert fits_handle._file.compression == 'gzip'\n assert len(fits_handle) == 5\n\n def test_writeto_append_mode_gzip(self):\n \"\"\"Regression test for\n https://github.com/spacetelescope/PyFITS/issues/33\n\n Check that a new GzipFile opened in append mode can be used to write\n out a new FITS file.\n \"\"\"\n\n # Note: when opening a GzipFile the 'b+' is superfluous, but this was\n # still how the original test case looked\n # Note: with statement not supported on GzipFile in older Python\n # versions\n fileobj = gzip.GzipFile(self.temp('test.fits.gz'), 'ab+')\n h = fits.PrimaryHDU()\n try:\n h.writeto(fileobj)\n finally:\n fileobj.close()\n\n with fits.open(self.temp('test.fits.gz')) as hdul:\n assert hdul[0].header == h.header\n\n def test_fits_update_mode_gzip(self):\n \"\"\"Test updating a GZipped FITS file\"\"\"\n\n with fits.open(self._make_gzip_file('update.gz'), mode='update') as fits_handle:\n hdu = fits.ImageHDU(data=[x for x in range(100)])\n fits_handle.append(hdu)\n\n with fits.open(self.temp('update.gz')) as new_handle:\n assert len(new_handle) == 6\n assert (new_handle[-1].data == [x for x in range(100)]).all()\n\n def test_fits_append_mode_gzip(self):\n \"\"\"Make sure that attempting to open an existing GZipped FITS file in\n 'append' mode raises an error\"\"\"\n\n with pytest.raises(OSError):\n with fits.open(self._make_gzip_file('append.gz'), mode='append') as _:\n pass\n\n @pytest.mark.skipif(not HAS_BZ2, reason='Python built without bz2 module')\n def test_open_bzipped(self):\n bzip_file = self._make_bzip2_file()\n with ignore_warnings():\n with fits.open(bzip_file) as fits_handle:\n assert fits_handle._file.compression == 'bzip2'\n assert len(fits_handle) == 5\n\n with fits.open(bz2.BZ2File(bzip_file)) as fits_handle:\n assert fits_handle._file.compression == 'bzip2'\n assert len(fits_handle) == 5\n\n @pytest.mark.skipif(not HAS_BZ2, reason='Python built without bz2 module')\n def test_open_bzipped_from_handle(self):\n with open(self._make_bzip2_file(), 'rb') as handle:\n with fits.open(handle) as fits_handle:\n assert fits_handle._file.compression == 'bzip2'\n assert len(fits_handle) == 5\n\n @pytest.mark.skipif(not HAS_BZ2, reason='Python built without bz2 module')\n def test_detect_bzipped(self):\n \"\"\"Test detection of a bzip2 file when the extension is not .bz2.\"\"\"\n with ignore_warnings():\n with fits.open(self._make_bzip2_file('test0.xx')) as fits_handle:\n assert fits_handle._file.compression == 'bzip2'\n assert len(fits_handle) == 5\n\n @pytest.mark.skipif(not HAS_BZ2, reason='Python built without bz2 module')\n def test_writeto_bzip2_fileobj(self):\n \"\"\"Test writing to a bz2.BZ2File file like object\"\"\"\n fileobj = bz2.BZ2File(self.temp('test.fits.bz2'), 'w')\n h = fits.PrimaryHDU()\n try:\n h.writeto(fileobj)\n finally:\n fileobj.close()\n\n with fits.open(self.temp('test.fits.bz2')) as hdul:\n assert hdul[0].header == h.header\n\n @pytest.mark.skipif(not HAS_BZ2, reason='Python built without bz2 module')\n def test_writeto_bzip2_filename(self):\n \"\"\"Test writing to a bzip2 file by name\"\"\"\n filename = self.temp('testname.fits.bz2')\n h = fits.PrimaryHDU()\n h.writeto(filename)\n\n with fits.open(self.temp('testname.fits.bz2')) as hdul:\n assert hdul[0].header == h.header\n\n def test_open_zipped(self):\n zip_file = self._make_zip_file()\n with ignore_warnings():\n with fits.open(zip_file) as fits_handle:\n assert fits_handle._file.compression == 'zip'\n assert len(fits_handle) == 5\n with fits.open(zipfile.ZipFile(zip_file)) as fits_handle:\n assert fits_handle._file.compression == 'zip'\n assert len(fits_handle) == 5\n\n def test_open_zipped_from_handle(self):\n with open(self._make_zip_file(), 'rb') as handle:\n with fits.open(handle) as fits_handle:\n assert fits_handle._file.compression == 'zip'\n assert len(fits_handle) == 5\n\n def test_detect_zipped(self):\n \"\"\"Test detection of a zip file when the extension is not .zip.\"\"\"\n\n zf = self._make_zip_file(filename='test0.fz')\n with ignore_warnings():\n assert len(fits.open(zf)) == 5\n\n def test_open_zipped_writeable(self):\n \"\"\"Opening zipped files in a writeable mode should fail.\"\"\"\n\n zf = self._make_zip_file()\n pytest.raises(OSError, fits.open, zf, 'update')\n pytest.raises(OSError, fits.open, zf, 'append')\n\n zf = zipfile.ZipFile(zf, 'a')\n pytest.raises(OSError, fits.open, zf, 'update')\n pytest.raises(OSError, fits.open, zf, 'append')\n\n def test_read_open_astropy_gzip_file(self):\n \"\"\"\n Regression test for https://github.com/astropy/astropy/issues/2774\n\n This tests reading from a ``GzipFile`` object from Astropy's\n compatibility copy of the ``gzip`` module.\n \"\"\"\n gf = gzip.GzipFile(self._make_gzip_file())\n try:\n assert len(fits.open(gf)) == 5\n finally:\n gf.close()\n\n @raises(OSError)\n def test_open_multiple_member_zipfile(self):\n \"\"\"\n Opening zip files containing more than one member files should fail\n as there's no obvious way to specify which file is the FITS file to\n read.\n \"\"\"\n\n zfile = zipfile.ZipFile(self.temp('test0.zip'), 'w')\n zfile.write(self.data('test0.fits'))\n zfile.writestr('foo', 'bar')\n zfile.close()\n\n fits.open(zfile.filename)\n\n def test_read_open_file(self):\n \"\"\"Read from an existing file object.\"\"\"\n\n with open(self.data('test0.fits'), 'rb') as f:\n assert len(fits.open(f)) == 5\n\n def test_read_closed_file(self):\n \"\"\"Read from an existing file object that's been closed.\"\"\"\n\n f = open(self.data('test0.fits'), 'rb')\n f.close()\n with fits.open(f) as f2:\n assert len(f2) == 5\n\n def test_read_open_gzip_file(self):\n \"\"\"Read from an open gzip file object.\"\"\"\n\n gf = gzip.GzipFile(self._make_gzip_file())\n try:\n assert len(fits.open(gf)) == 5\n finally:\n gf.close()\n\n def test_open_gzip_file_for_writing(self):\n \"\"\"Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/195.\"\"\"\n\n gf = self._make_gzip_file()\n with fits.open(gf, mode='update') as h:\n h[0].header['EXPFLAG'] = 'ABNORMAL'\n h[1].data[0, 0] = 1\n with fits.open(gf) as h:\n # Just to make sur ethe update worked; if updates work\n # normal writes should work too...\n assert h[0].header['EXPFLAG'] == 'ABNORMAL'\n assert h[1].data[0, 0] == 1\n\n def test_write_read_gzip_file(self):\n \"\"\"\n Regression test for https://github.com/astropy/astropy/issues/2794\n\n Ensure files written through gzip are readable.\n \"\"\"\n\n data = np.arange(100)\n hdu = fits.PrimaryHDU(data=data)\n hdu.writeto(self.temp('test.fits.gz'))\n\n with open(self.temp('test.fits.gz'), 'rb') as f:\n assert f.read(3) == GZIP_MAGIC\n\n with fits.open(self.temp('test.fits.gz')) as hdul:\n assert np.all(hdul[0].data == data)\n\n def test_read_file_like_object(self):\n \"\"\"Test reading a FITS file from a file-like object.\"\"\"\n\n filelike = io.BytesIO()\n with open(self.data('test0.fits'), 'rb') as f:\n filelike.write(f.read())\n filelike.seek(0)\n with ignore_warnings():\n assert len(fits.open(filelike)) == 5\n\n def test_updated_file_permissions(self):\n \"\"\"\n Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/79\n\n Tests that when a FITS file is modified in update mode, the file\n permissions are preserved.\n \"\"\"\n\n filename = self.temp('test.fits')\n hdul = [fits.PrimaryHDU(), fits.ImageHDU()]\n hdul = fits.HDUList(hdul)\n hdul.writeto(filename)\n\n old_mode = os.stat(filename).st_mode\n\n hdul = fits.open(filename, mode='update')\n hdul.insert(1, fits.ImageHDU())\n hdul.flush()\n hdul.close()\n\n assert old_mode == os.stat(filename).st_mode\n\n def test_fileobj_mode_guessing(self):\n \"\"\"Tests whether a file opened without a specified io.fits mode\n ('readonly', etc.) is opened in a mode appropriate for the given file\n object.\n \"\"\"\n\n self.copy_file('test0.fits')\n\n # Opening in text mode should outright fail\n for mode in ('r', 'w', 'a'):\n with open(self.temp('test0.fits'), mode) as f:\n pytest.raises(ValueError, fits.HDUList.fromfile, f)\n\n # Need to re-copy the file since opening it in 'w' mode blew it away\n self.copy_file('test0.fits')\n\n with open(self.temp('test0.fits'), 'rb') as f:\n with fits.HDUList.fromfile(f) as h:\n assert h.fileinfo(0)['filemode'] == 'readonly'\n\n for mode in ('wb', 'ab'):\n with open(self.temp('test0.fits'), mode) as f:\n with fits.HDUList.fromfile(f) as h:\n # Basically opening empty files for output streaming\n assert len(h) == 0\n\n # Need to re-copy the file since opening it in 'w' mode blew it away\n self.copy_file('test0.fits')\n\n with open(self.temp('test0.fits'), 'wb+') as f:\n with fits.HDUList.fromfile(f) as h:\n # wb+ still causes an existing file to be overwritten so there\n # are no HDUs\n assert len(h) == 0\n\n # Need to re-copy the file since opening it in 'w' mode blew it away\n self.copy_file('test0.fits')\n\n with open(self.temp('test0.fits'), 'rb+') as f:\n with fits.HDUList.fromfile(f) as h:\n assert h.fileinfo(0)['filemode'] == 'update'\n\n with open(self.temp('test0.fits'), 'ab+') as f:\n with fits.HDUList.fromfile(f) as h:\n assert h.fileinfo(0)['filemode'] == 'append'\n\n def test_mmap_unwriteable(self):\n \"\"\"Regression test for https://github.com/astropy/astropy/issues/968\n\n Temporarily patches mmap.mmap to exhibit platform-specific bad\n behavior.\n \"\"\"\n\n class MockMmap(mmap.mmap):\n def flush(self):\n raise OSError('flush is broken on this platform')\n\n old_mmap = mmap.mmap\n mmap.mmap = MockMmap\n\n # Force the mmap test to be rerun\n _File.__dict__['_mmap_available']._cache.clear()\n\n try:\n self.copy_file('test0.fits')\n with catch_warnings() as w:\n with fits.open(self.temp('test0.fits'), mode='update',\n memmap=True) as h:\n h[1].data[0, 0] = 999\n\n assert len(w) == 1\n assert 'mmap.flush is unavailable' in str(w[0].message)\n\n # Double check that writing without mmap still worked\n with fits.open(self.temp('test0.fits')) as h:\n assert h[1].data[0, 0] == 999\n finally:\n mmap.mmap = old_mmap\n _File.__dict__['_mmap_available']._cache.clear()\n\n @pytest.mark.openfiles_ignore\n def test_mmap_allocate_error(self):\n \"\"\"\n Regression test for https://github.com/astropy/astropy/issues/1380\n\n Temporarily patches mmap.mmap to raise an OSError if mode is ACCESS_COPY.\n \"\"\"\n\n mmap_original = mmap.mmap\n\n # We patch mmap here to raise an error if access=mmap.ACCESS_COPY, which\n # emulates an issue that an OSError is raised if the available address\n # space is less than the size of the file even if memory mapping is used.\n\n def mmap_patched(*args, **kwargs):\n if kwargs.get('access') == mmap.ACCESS_COPY:\n exc = OSError()\n exc.errno = errno.ENOMEM\n raise exc\n else:\n return mmap_original(*args, **kwargs)\n\n with fits.open(self.data('test0.fits'), memmap=True) as hdulist:\n with patch.object(mmap, 'mmap', side_effect=mmap_patched) as p:\n with pytest.warns(AstropyUserWarning, match=r\"Could not memory \"\n r\"map array with mode='readonly'\"):\n data = hdulist[1].data\n p.reset_mock()\n assert not data.flags.writeable\n\n def test_mmap_closing(self):\n \"\"\"\n Tests that the mmap reference is closed/removed when there aren't any\n HDU data references left.\n \"\"\"\n\n if not _File._mmap_available:\n pytest.xfail('not expected to work on platforms without mmap '\n 'support')\n\n with fits.open(self.data('test0.fits'), memmap=True) as hdul:\n assert hdul._file._mmap is None\n\n hdul[1].data\n assert hdul._file._mmap is not None\n\n del hdul[1].data\n # Should be no more references to data in the file so close the\n # mmap\n assert hdul._file._mmap is None\n\n hdul[1].data\n hdul[2].data\n del hdul[1].data\n # hdul[2].data is still references so keep the mmap open\n assert hdul._file._mmap is not None\n del hdul[2].data\n assert hdul._file._mmap is None\n\n assert hdul._file._mmap is None\n\n with fits.open(self.data('test0.fits'), memmap=True) as hdul:\n hdul[1].data\n\n # When the only reference to the data is on the hdu object, and the\n # hdulist it belongs to has been closed, the mmap should be closed as\n # well\n assert hdul._file._mmap is None\n\n with fits.open(self.data('test0.fits'), memmap=True) as hdul:\n data = hdul[1].data\n # also make a copy\n data_copy = data.copy()\n\n # The HDUList is closed; in fact, get rid of it completely\n del hdul\n\n # The data array should still work though...\n assert np.all(data == data_copy)\n\n def test_uncloseable_file(self):\n \"\"\"\n Regression test for https://github.com/astropy/astropy/issues/2356\n\n Demonstrates that FITS files can still be read from \"file-like\" objects\n that don't have an obvious \"open\" or \"closed\" state.\n \"\"\"\n\n class MyFileLike:\n def __init__(self, foobar):\n self._foobar = foobar\n\n def read(self, n):\n return self._foobar.read(n)\n\n def seek(self, offset, whence=os.SEEK_SET):\n self._foobar.seek(offset, whence)\n\n def tell(self):\n return self._foobar.tell()\n\n with open(self.data('test0.fits'), 'rb') as f:\n fileobj = MyFileLike(f)\n\n with fits.open(fileobj) as hdul1:\n with fits.open(self.data('test0.fits')) as hdul2:\n assert hdul1.info(output=False) == hdul2.info(output=False)\n for hdu1, hdu2 in zip(hdul1, hdul2):\n assert hdu1.header == hdu2.header\n if hdu1.data is not None and hdu2.data is not None:\n assert np.all(hdu1.data == hdu2.data)\n\n def test_write_bytesio_discontiguous(self):\n \"\"\"\n Regression test related to\n https://github.com/astropy/astropy/issues/2794#issuecomment-55441539\n\n Demonstrates that writing an HDU containing a discontiguous Numpy array\n should work properly.\n \"\"\"\n\n data = np.arange(100)[::3]\n hdu = fits.PrimaryHDU(data=data)\n fileobj = io.BytesIO()\n hdu.writeto(fileobj)\n\n fileobj.seek(0)\n\n with fits.open(fileobj) as h:\n assert np.all(h[0].data == data)\n\n def test_write_bytesio(self):\n \"\"\"\n Regression test for https://github.com/astropy/astropy/issues/2463\n\n Test againt `io.BytesIO`. `io.StringIO` is not supported.\n \"\"\"\n\n self._test_write_string_bytes_io(io.BytesIO())\n\n @pytest.mark.skipif('sys.platform.startswith(\"win32\")')\n def test_filename_with_colon(self):\n \"\"\"\n Test reading and writing a file with a colon in the filename.\n\n Regression test for https://github.com/astropy/astropy/issues/3122\n \"\"\"\n\n # Skip on Windows since colons in filenames makes NTFS sad.\n\n filename = 'APEXHET.2014-04-01T15:18:01.000.fits'\n hdu = fits.PrimaryHDU(data=np.arange(10))\n hdu.writeto(self.temp(filename))\n\n with fits.open(self.temp(filename)) as hdul:\n assert np.all(hdul[0].data == hdu.data)\n\n def test_writeto_full_disk(self, monkeypatch):\n \"\"\"\n Test that it gives a readable error when trying to write an hdulist\n to a full disk.\n \"\"\"\n\n def _writeto(self, array):\n raise OSError(\"Fake error raised when writing file.\")\n\n def get_free_space_in_dir(path):\n return 0\n\n with pytest.raises(OSError) as exc:\n monkeypatch.setattr(fits.hdu.base._BaseHDU, \"_writeto\", _writeto)\n monkeypatch.setattr(data, \"get_free_space_in_dir\", get_free_space_in_dir)\n\n n = np.arange(0, 1000, dtype='int64')\n hdu = fits.PrimaryHDU(n)\n hdulist = fits.HDUList(hdu)\n filename = self.temp('test.fits')\n\n with open(filename, mode='wb') as fileobj:\n hdulist.writeto(fileobj)\n\n assert (\"Not enough space on disk: requested 8000, available 0. \"\n \"Fake error raised when writing file.\") == exc.value.args[0]\n\n def test_flush_full_disk(self, monkeypatch):\n \"\"\"\n Test that it gives a readable error when trying to update an hdulist\n to a full disk.\n \"\"\"\n filename = self.temp('test.fits')\n hdul = [fits.PrimaryHDU(), fits.ImageHDU()]\n hdul = fits.HDUList(hdul)\n hdul[0].data = np.arange(0, 1000, dtype='int64')\n hdul.writeto(filename)\n\n def _writedata(self, fileobj):\n raise OSError(\"Fake error raised when writing file.\")\n\n def get_free_space_in_dir(path):\n return 0\n\n monkeypatch.setattr(fits.hdu.base._BaseHDU, \"_writedata\", _writedata)\n monkeypatch.setattr(data, \"get_free_space_in_dir\",\n get_free_space_in_dir)\n\n with pytest.raises(OSError) as exc:\n with fits.open(filename, mode='update') as hdul:\n hdul[0].data = np.arange(0, 1000, dtype='int64')\n hdul.insert(1, fits.ImageHDU())\n hdul.flush()\n\n assert (\"Not enough space on disk: requested 8000, available 0. \"\n \"Fake error raised when writing file.\") == exc.value.args[0]\n\n def _test_write_string_bytes_io(self, fileobj):\n \"\"\"\n Implemented for both test_write_stringio and test_write_bytesio.\n \"\"\"\n\n with fits.open(self.data('test0.fits')) as hdul:\n hdul.writeto(fileobj)\n hdul2 = fits.HDUList.fromstring(fileobj.getvalue())\n assert FITSDiff(hdul, hdul2).identical\n\n def _make_gzip_file(self, filename='test0.fits.gz'):\n gzfile = self.temp(filename)\n with open(self.data('test0.fits'), 'rb') as f:\n gz = gzip.open(gzfile, 'wb')\n gz.write(f.read())\n gz.close()\n\n return gzfile\n\n def _make_zip_file(self, mode='copyonwrite', filename='test0.fits.zip'):\n zfile = zipfile.ZipFile(self.temp(filename), 'w')\n zfile.write(self.data('test0.fits'))\n zfile.close()\n\n return zfile.filename\n\n def _make_bzip2_file(self, filename='test0.fits.bz2'):\n bzfile = self.temp(filename)\n with open(self.data('test0.fits'), 'rb') as f:\n bz = bz2.BZ2File(bzfile, 'w')\n bz.write(f.read())\n bz.close()\n\n return bzfile\n\n def test_simulateonly(self):\n \"\"\"Write to None simulates writing.\"\"\"\n\n with fits.open(self.data('test0.fits')) as hdul:\n hdul.writeto(None)\n hdul[0].writeto(None)\n hdul[0].header.tofile(None)\n\n\nclass TestStreamingFunctions(FitsTestCase):\n \"\"\"Test functionality of the StreamingHDU class.\"\"\"\n\n def test_streaming_hdu(self):\n shdu = self._make_streaming_hdu(self.temp('new.fits'))\n assert isinstance(shdu.size, int)\n assert shdu.size == 100\n shdu.close()\n\n @raises(ValueError)\n def test_streaming_hdu_file_wrong_mode(self):\n \"\"\"\n Test that streaming an HDU to a file opened in the wrong mode fails as\n expected.\n \"\"\"\n\n with open(self.temp('new.fits'), 'wb') as f:\n header = fits.Header()\n fits.StreamingHDU(f, header)\n\n def test_streaming_hdu_write_file(self):\n \"\"\"Test streaming an HDU to an open file object.\"\"\"\n\n arr = np.zeros((5, 5), dtype=np.int32)\n with open(self.temp('new.fits'), 'ab+') as f:\n shdu = self._make_streaming_hdu(f)\n shdu.write(arr)\n assert shdu.writecomplete\n assert shdu.size == 100\n with fits.open(self.temp('new.fits')) as hdul:\n assert len(hdul) == 1\n assert (hdul[0].data == arr).all()\n\n def test_streaming_hdu_write_file_like(self):\n \"\"\"Test streaming an HDU to an open file-like object.\"\"\"\n\n arr = np.zeros((5, 5), dtype=np.int32)\n # The file-like object underlying a StreamingHDU must be in binary mode\n sf = io.BytesIO()\n shdu = self._make_streaming_hdu(sf)\n shdu.write(arr)\n assert shdu.writecomplete\n assert shdu.size == 100\n\n sf.seek(0)\n hdul = fits.open(sf)\n assert len(hdul) == 1\n assert (hdul[0].data == arr).all()\n\n def test_streaming_hdu_append_extension(self):\n arr = np.zeros((5, 5), dtype=np.int32)\n with open(self.temp('new.fits'), 'ab+') as f:\n shdu = self._make_streaming_hdu(f)\n shdu.write(arr)\n # Doing this again should update the file with an extension\n with open(self.temp('new.fits'), 'ab+') as f:\n shdu = self._make_streaming_hdu(f)\n shdu.write(arr)\n\n def test_fix_invalid_extname(self, capsys):\n phdu = fits.PrimaryHDU()\n ihdu = fits.ImageHDU()\n ihdu.header['EXTNAME'] = 12345678\n hdul = fits.HDUList([phdu, ihdu])\n filename = self.temp('temp.fits')\n\n pytest.raises(fits.VerifyError, hdul.writeto, filename,\n output_verify='exception')\n with pytest.warns(fits.verify.VerifyWarning,\n match=r'Verification reported errors'):\n hdul.writeto(filename, output_verify='fix')\n with fits.open(filename):\n assert hdul[1].name == '12345678'\n assert hdul[1].header['EXTNAME'] == '12345678'\n\n hdul.close()\n\n def _make_streaming_hdu(self, fileobj):\n hd = fits.Header()\n hd['SIMPLE'] = (True, 'conforms to FITS standard')\n hd['BITPIX'] = (32, 'array data type')\n hd['NAXIS'] = (2, 'number of array dimensions')\n hd['NAXIS1'] = 5\n hd['NAXIS2'] = 5\n hd['EXTEND'] = True\n return fits.StreamingHDU(fileobj, hd)\n\n def test_blank_ignore(self):\n\n with fits.open(self.data('blank.fits'), ignore_blank=True) as f:\n assert f[0].data.flat[0] == 2\n\n def test_error_if_memmap_impossible(self):\n pth = self.data('blank.fits')\n with fits.open(pth, memmap=True) as hdul:\n with pytest.raises(ValueError):\n hdul[0].data\n\n # However, it should not fail if do_not_scale_image_data was used:\n # See https://github.com/astropy/astropy/issues/3766\n with fits.open(pth, memmap=True, do_not_scale_image_data=True) as hdul:\n hdul[0].data # Just make sure it doesn't crash\n" ]
[ [ "numpy.logical_not", "numpy.all", "numpy.isscalar", "numpy.array", "numpy.zeros" ], [ "numpy.all", "numpy.arange", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LauraOlivera/gammapy
[ "8aadf0ec524bcf51d0ac5655a04507d5d449e7ed" ]
[ "gammapy/estimators/tests/test_flux_point.py" ]
[ "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport pytest\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport astropy.units as u\nfrom astropy.table import Table\nfrom gammapy.catalog.fermi import SourceCatalog3FGL\nfrom gammapy.estimators import FluxPoints\nfrom gammapy.modeling.models import SpectralModel\nfrom gammapy.utils.scripts import make_path\nfrom gammapy.utils.testing import (\n assert_quantity_allclose,\n mpl_plot_check,\n requires_data,\n requires_dependency,\n)\n\nFLUX_POINTS_FILES = [\n \"diff_flux_points.ecsv\",\n \"diff_flux_points.fits\",\n \"flux_points.ecsv\",\n \"flux_points.fits\",\n]\n\n\nclass LWTestModel(SpectralModel):\n @staticmethod\n def evaluate(x):\n return 1e4 * np.exp(-6 * x)\n\n def integral(self, xmin, xmax, **kwargs):\n return -1.0 / 6 * 1e4 * (np.exp(-6 * xmax) - np.exp(-6 * xmin))\n\n def inverse(self, y):\n return -1.0 / 6 * np.log(y * 1e-4)\n\n\nclass XSqrTestModel(SpectralModel):\n @staticmethod\n def evaluate(x):\n return x ** 2\n\n def integral(self, xmin, xmax, **kwargs):\n return 1.0 / 3 * (xmax ** 3 - xmin ** 2)\n\n def inverse(self, y):\n return np.sqrt(y)\n\n\nclass ExpTestModel(SpectralModel):\n @staticmethod\n def evaluate(x):\n return np.exp(x * u.Unit(\"1 / TeV\"))\n\n def integral(self, xmin, xmax, **kwargs):\n return np.exp(xmax * u.Unit(\"1 / TeV\")) - np.exp(xmin * u.Unit(\"1 / TeV\"))\n\n def inverse(self, y):\n return np.log(y * u.TeV) * u.TeV\n\n\ndef test_energy_ref_lafferty():\n \"\"\"\n Tests Lafferty & Wyatt x-point method.\n\n Using input function g(x) = 10^4 exp(-6x) against\n check values from paper Lafferty & Wyatt. Nucl. Instr. and Meth. in Phys.\n Res. A 355 (1995) 541-547, p. 542 Table 1\n \"\"\"\n # These are the results from the paper\n desired = np.array([0.048, 0.190, 0.428, 0.762])\n\n model = LWTestModel()\n energy_min = np.array([0.0, 0.1, 0.3, 0.6])\n energy_max = np.array([0.1, 0.3, 0.6, 1.0])\n actual = FluxPoints._energy_ref_lafferty(model, energy_min, energy_max)\n assert_allclose(actual, desired, atol=1e-3)\n\n\[email protected]\ndef test_dnde_from_flux():\n \"\"\"Tests y-value normalization adjustment method.\n \"\"\"\n table = Table()\n table[\"e_min\"] = np.array([10, 20, 30, 40])\n table[\"e_max\"] = np.array([20, 30, 40, 50])\n table[\"flux\"] = np.array([42, 52, 62, 72]) # 'True' integral flux in this test bin\n\n # Get values\n model = XSqrTestModel()\n table[\"e_ref\"] = FluxPoints._energy_ref_lafferty(model, table[\"e_min\"], table[\"e_max\"])\n dnde = FluxPoints.from_table(table, reference_model=model)\n\n # Set up test case comparison\n dnde_model = model(table[\"e_ref\"])\n\n # Test comparison result\n desired = model.integral(table[\"e_min\"], table[\"e_max\"])\n # Test output result\n actual = table[\"flux\"] * (dnde_model / dnde)\n # Compare\n assert_allclose(actual, desired, rtol=1e-6)\n\n\[email protected]\[email protected](\"method\", [\"table\", \"lafferty\", \"log_center\"])\ndef test_compute_flux_points_dnde_exp(method):\n \"\"\"\n Tests against analytical result or result from a powerlaw.\n \"\"\"\n model = ExpTestModel()\n\n energy_min = [1.0, 10.0] * u.TeV\n energy_max = [10.0, 100.0] * u.TeV\n\n table = Table()\n table.meta[\"SED_TYPE\"] = \"flux\"\n table[\"e_min\"] = energy_min\n table[\"e_max\"] = energy_max\n\n flux = model.integral(energy_min, energy_max)\n table[\"flux\"] = flux\n\n if method == \"log_center\":\n energy_ref = np.sqrt(energy_min * energy_max)\n elif method == \"table\":\n energy_ref = [2.0, 20.0] * u.TeV\n elif method == \"lafferty\":\n energy_ref = FluxPoints._energy_ref_lafferty(model, energy_min, energy_max)\n\n table[\"e_ref\"] = energy_ref\n\n result = FluxPoints.from_table(table, reference_model=model)\n\n # Test energy\n actual = result.energy_ref\n assert_quantity_allclose(actual, energy_ref, rtol=1e-8)\n\n # Test flux\n actual = result.dnde\n desired = model(energy_ref)\n assert_quantity_allclose(actual, desired, rtol=1e-8)\n\n\n@requires_data()\ndef test_fermi_to_dnde():\n from gammapy.catalog import SourceCatalog4FGL\n\n catalog_4fgl = SourceCatalog4FGL(\"$GAMMAPY_DATA/catalogs/fermi/gll_psc_v20.fit.gz\")\n src = catalog_4fgl[\"FGES J1553.8-5325\"]\n fp = src.flux_points\n\n assert_allclose(\n fp.dnde.quantity[1, 0, 0],\n 4.567393e-10 * u.Unit(\"cm-2 s-1 MeV-1\"),\n rtol=1e-5,\n )\n\n\[email protected](params=FLUX_POINTS_FILES, scope=\"session\")\ndef flux_points(request):\n path = \"$GAMMAPY_DATA/tests/spectrum/flux_points/\" + request.param\n return FluxPoints.read(path)\n\n\[email protected](scope=\"session\")\ndef flux_points_likelihood():\n path = \"$GAMMAPY_DATA/tests/spectrum/flux_points/binlike.fits\"\n return FluxPoints.read(path)\n\n\n@requires_data()\nclass TestFluxPoints:\n def test_info(self, flux_points):\n info = str(flux_points)\n assert \"geom\" in info\n assert \"axes\" in info\n assert \"ref. model\" in info\n assert \"quantities\" in info\n\n def test_energy_ref(self, flux_points):\n actual = flux_points.energy_ref\n desired = np.sqrt(flux_points.energy_min * flux_points.energy_max)\n assert_quantity_allclose(actual, desired)\n\n def test_energy_min(self, flux_points):\n actual = flux_points.energy_min\n desired = 299530.97 * u.MeV\n assert_quantity_allclose(actual.sum(), desired)\n\n def test_energy_max(self, flux_points):\n actual = flux_points.energy_max\n desired = 399430.975 * u.MeV\n assert_quantity_allclose(actual.sum(), desired)\n\n def test_write_fits(self, tmp_path, flux_points):\n flux_points.write(tmp_path / \"tmp.fits\", sed_type=flux_points.sed_type_init)\n actual = FluxPoints.read(tmp_path / \"tmp.fits\")\n assert str(flux_points) == str(actual)\n\n def test_write_ecsv(self, tmp_path, flux_points):\n flux_points.write(tmp_path / \"flux_points.ecsv\", sed_type=flux_points.sed_type_init)\n actual = FluxPoints.read(tmp_path / \"flux_points.ecsv\")\n assert str(flux_points) == str(actual)\n\n def test_quantity_access(self, flux_points_likelihood):\n assert flux_points_likelihood.sqrt_ts\n assert flux_points_likelihood.ts\n assert flux_points_likelihood.stat\n assert_allclose(flux_points_likelihood.n_sigma_ul, 2)\n assert flux_points_likelihood.sed_type_init == \"likelihood\"\n\n @requires_dependency(\"matplotlib\")\n def test_plot(self, flux_points):\n with mpl_plot_check():\n flux_points.plot()\n\n @requires_dependency(\"matplotlib\")\n def test_plot_likelihood(self, flux_points_likelihood):\n with mpl_plot_check():\n flux_points_likelihood.plot_ts_profiles()\n\n @requires_dependency(\"matplotlib\")\n def test_plot_likelihood_error(self, flux_points_likelihood):\n del flux_points_likelihood._data[\"stat_scan\"]\n with pytest.raises(AttributeError):\n flux_points_likelihood.plot_ts_profiles()\n\n\n@requires_data()\ndef test_compute_flux_points_dnde_fermi():\n \"\"\"\n Test compute_flux_points_dnde on fermi source.\n \"\"\"\n fermi_3fgl = SourceCatalog3FGL()\n source = fermi_3fgl[\"3FGL J0835.3-4510\"]\n flux_points = source.flux_points\n table = source.flux_points_table\n\n for column in [\"e2dnde\", \"e2dnde_errn\", \"e2dnde_errp\", \"e2dnde_ul\"]:\n actual = table[column].quantity\n desired = getattr(flux_points, column).quantity.squeeze()\n assert_quantity_allclose(actual[:-1], desired[:-1], rtol=0.05)\n\n@requires_data()\n@requires_dependency(\"matplotlib\")\ndef test_plot_fp_no_ul():\n path = make_path(\"$GAMMAPY_DATA/tests/spectrum/flux_points/diff_flux_points.fits\")\n table = Table.read(path)\n table.remove_column('dnde_ul')\n fp = FluxPoints.from_table(table, sed_type='dnde')\n\n with mpl_plot_check():\n fp.plot()\n\n" ]
[ [ "numpy.log", "numpy.sqrt", "numpy.testing.assert_allclose", "numpy.array", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MaxxWilson/ASE389Project
[ "13c3c72887e27fbed2eef63c1e27b4a185036a39" ]
[ "pnc/draco3_lb_pnc/draco3_lb_controller.py" ]
[ "import numpy as np\n\nfrom util import util\nfrom config.draco3_lb_config import PnCConfig, WBCConfig\nfrom pnc.wbc.ihwbc.ihwbc import IHWBC\nfrom pnc.wbc.ihwbc.joint_integrator import JointIntegrator\n\n\nclass Draco3LBController(object):\n def __init__(self, tci_container, robot):\n self._tci_container = tci_container\n self._robot = robot\n\n # Initialize WBC\n l_jp_idx, l_jd_idx, r_jp_idx, r_jd_idx = self._robot.get_q_dot_idx(\n ['l_knee_fe_jp', 'l_knee_fe_jd', 'r_knee_fe_jp', 'r_knee_fe_jd'])\n act_list = [False] * robot.n_floating + [True] * robot.n_a\n act_list[l_jd_idx] = False\n act_list[r_jd_idx] = False\n\n n_q_dot = len(act_list)\n n_active = np.count_nonzero(np.array(act_list))\n n_passive = n_q_dot - n_active - 6\n\n self._sa = np.zeros((n_active, n_q_dot))\n self._sv = np.zeros((n_passive, n_q_dot))\n j, k = 0, 0\n for i in range(n_q_dot):\n if i >= 6:\n if act_list[i]:\n self._sa[j, i] = 1.\n j += 1\n else:\n self._sv[k, i] = 1.\n k += 1\n self._sf = np.zeros((6, n_q_dot))\n self._sf[0:6, 0:6] = np.eye(6)\n\n self._ihwbc = IHWBC(self._sf, self._sa, self._sv, PnCConfig.SAVE_DATA)\n if WBCConfig.B_TRQ_LIMIT:\n self._ihwbc.trq_limit = np.dot(self._sa[:, 6:],\n self._robot.joint_trq_limit)\n self._ihwbc.lambda_q_ddot = WBCConfig.LAMBDA_Q_DDOT\n self._ihwbc.lambda_rf = WBCConfig.LAMBDA_RF\n\n # Initialize Joint Integrator\n self._joint_integrator = JointIntegrator(robot.n_a,\n PnCConfig.CONTROLLER_DT)\n self._joint_integrator.pos_cutoff_freq = WBCConfig.POS_CUTOFF_FREQ\n self._joint_integrator.vel_cutoff_freq = WBCConfig.VEL_CUTOFF_FREQ\n self._joint_integrator.max_pos_err = WBCConfig.MAX_POS_ERR\n self._joint_integrator.joint_pos_limit = self._robot.joint_pos_limit\n self._joint_integrator.joint_vel_limit = self._robot.joint_vel_limit\n\n self._b_first_visit = True\n\n def get_command(self):\n if self._b_first_visit:\n self.first_visit()\n\n # Dynamics properties\n mass_matrix = self._robot.get_mass_matrix()\n mass_matrix_inv = np.linalg.inv(mass_matrix)\n coriolis = self._robot.get_coriolis()\n gravity = self._robot.get_gravity()\n self._ihwbc.update_setting(mass_matrix, mass_matrix_inv, coriolis,\n gravity)\n # Task, Contact, and Internal Constraint Setup\n w_hierarchy_list = []\n for task in self._tci_container.task_list:\n task.update_jacobian()\n task.update_cmd()\n w_hierarchy_list.append(task.w_hierarchy)\n self._ihwbc.w_hierarchy = np.array(w_hierarchy_list)\n for contact in self._tci_container.contact_list:\n contact.update_contact()\n for internal_constraint in self._tci_container.internal_constraint_list:\n internal_constraint.update_internal_constraint()\n # WBC commands\n joint_trq_cmd, joint_acc_cmd, rf_cmd = self._ihwbc.solve(\n self._tci_container.task_list, self._tci_container.contact_list,\n self._tci_container.internal_constraint_list)\n joint_trq_cmd = np.dot(self._sa[:, 6:].transpose(), joint_trq_cmd)\n joint_acc_cmd = np.dot(self._sa[:, 6:].transpose(), joint_acc_cmd)\n # Double integration\n joint_vel_cmd, joint_pos_cmd = self._joint_integrator.integrate(\n joint_acc_cmd, self._robot.joint_velocities,\n self._robot.joint_positions)\n\n command = self._robot.create_cmd_ordered_dict(joint_pos_cmd,\n joint_vel_cmd,\n joint_trq_cmd)\n return command\n\n def first_visit(self):\n joint_pos_ini = self._robot.joint_positions\n self._joint_integrator.initialize_states(np.zeros(self._robot.n_a),\n joint_pos_ini)\n\n self._b_first_visit = False\n" ]
[ [ "numpy.dot", "numpy.linalg.inv", "numpy.eye", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Barry-lab/Publication_TanniDeCothiBarry2021
[ "425bc0bd9a74b837d912820e9ea1539a111fcb1f", "425bc0bd9a74b837d912820e9ea1539a111fcb1f", "425bc0bd9a74b837d912820e9ea1539a111fcb1f" ]
[ "visual_change_analysis/main.py", "electrophysiology_analysis/barrylab_ephys_analysis/spatial/fields.py", "electrophysiology_analysis/barrylab_ephys_analysis/lfp/oscillations.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy.stats import pearsonr\nfrom bin_data import bin_data\n\n# import pixel data \nright_z_pixel_change = np.load(\"right_z_pixel_change.npy\")\nleft_z_pixel_change = np.load(\"left_z_pixel_change.npy\")\nfront_z_pixel_change = np.load(\"front_z_pixel_change.npy\")\n\n# average pixel change across front, left & right fovs\npixel_change = np.vstack((left_z_pixel_change, front_z_pixel_change, right_z_pixel_change)).mean(axis=0)\n\n# import rate change data \ndat = pd.read_pickle(\"df_population_vector_change.p\")\n\n# Clean the data (sequential data points are 1cm apart along trajectory)\ndat = dat[dat.environment == 'D']\ndf = dat.filter(['animal', 'x_coord', 'y_coord', 'direction', 'timestamp'], axis=1)\ndat = dat[~df.isnull().any(axis=1)]\ngood_pixel_ids = np.array(np.diff(dat.x_coord)**2 + np.diff(dat.y_coord)**2 < 1.01, dtype=bool)\npixel_change = pixel_change[good_pixel_ids]\ngood_rate_ids = np.append(False, good_pixel_ids)\nturning_rate = np.abs(np.diff(dat['direction'])) % 360\nturning_rate = turning_rate[good_pixel_ids]\ndat = dat[good_rate_ids]\n\n# z-score data\ndat['rate change\\n(euclidean)'] = (dat['rate change\\n(euclidean)'] - np.mean(dat['rate change\\n(euclidean)']))/np.std(dat['rate change\\n(euclidean)'])\npixel_change = (pixel_change - np.mean(pixel_change))/np.std(pixel_change)\n\n# Plot Occupancy\noccupancy = bin_data([dat.x_coord, dat.y_coord], bin_size = 4, limits = [(0, 350), (0, 250)])\nplt.imshow(occupancy.T, origin='upper', cmap=plt.get_cmap('jet'))\nplt.title('Occupancy')\nplt.show()\n\n# Plot pixel change across space\npixel_change_map = bin_data([dat.x_coord, dat.y_coord], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = pixel_change) / occupancy\nplt.imshow(pixel_change_map.T, origin='upper', cmap=plt.get_cmap('jet'))\nplt.axis('off')\nplt.clim([-1.5,1.5])\nplt.title('Pixel Change Map')\nplt.show()\n\n# Plot firing rate change across space\nrate_change_map = bin_data([dat.x_coord, dat.y_coord], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = dat['rate change\\n(euclidean)']) / occupancy\nplt.imshow(rate_change_map.T, origin='upper', cmap=plt.get_cmap('jet'))\nplt.axis('off')\nplt.clim([-1.5,1.5])\nplt.title('Rate Change Map')\nplt.show()\n\ncorr, _ = pearsonr(pixel_change, dat['rate change\\n(euclidean)'])\nprint('Rate Change vs Pixel Change Pearson r = %.3f' % corr)\n\n# Filter bits of trajectory by head direction\nnorth_ids = (np.degrees(dat.direction) % 360 >= 315) | (np.degrees(dat.direction) % 360 < 45)\nnorth_occupancy = bin_data([dat.x_coord[north_ids], dat.y_coord[north_ids]], bin_size = 4, limits = [(0, 350), (0, 250)])\nsouth_ids = (np.degrees(dat.direction) % 360 >= 135) & (np.degrees(dat.direction) % 360 < 225)\nsouth_occupancy = bin_data([dat.x_coord[south_ids], dat.y_coord[south_ids]], bin_size = 4, limits = [(0, 350), (0, 250)])\neast_ids = (np.degrees(dat.direction) % 360 >= 45) & (np.degrees(dat.direction) % 360 < 135)\neast_occupancy = bin_data([dat.x_coord[east_ids], dat.y_coord[east_ids]], bin_size = 4, limits = [(0, 350), (0, 250)])\nwest_ids = (np.degrees(dat.direction) % 360 >= 225) & (np.degrees(dat.direction) % 360 < 315)\nwest_occupancy = bin_data([dat.x_coord[west_ids], dat.y_coord[west_ids]], bin_size = 4, limits = [(0, 350), (0, 250)])\n\ncmap = plt.get_cmap('jet')\ncmap.set_bad('w',1.)\n\n# Calculate pixel and rate change maps by heading direction\nnorth_pix_map = bin_data([dat.x_coord[north_ids], dat.y_coord[north_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = pixel_change[north_ids]) / north_occupancy\nsouth_pix_map = bin_data([dat.x_coord[south_ids], dat.y_coord[south_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = pixel_change[south_ids]) / south_occupancy\neast_pix_map = bin_data([dat.x_coord[east_ids], dat.y_coord[east_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = pixel_change[east_ids]) / east_occupancy\nwest_pix_map = bin_data([dat.x_coord[west_ids], dat.y_coord[west_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = pixel_change[west_ids]) / west_occupancy\nnorth_rat_map = bin_data([dat.x_coord[north_ids], dat.y_coord[north_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = dat['rate change\\n(euclidean)'][north_ids]) / north_occupancy\nsouth_rat_map = bin_data([dat.x_coord[south_ids], dat.y_coord[south_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = dat['rate change\\n(euclidean)'][south_ids]) / south_occupancy\neast_rat_map = bin_data([dat.x_coord[east_ids], dat.y_coord[east_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = dat['rate change\\n(euclidean)'][east_ids]) / east_occupancy\nwest_rat_map = bin_data([dat.x_coord[west_ids], dat.y_coord[west_ids]], bin_size = 4, limits = [(0, 350), (0, 250)], var_to_bin = dat['rate change\\n(euclidean)'][west_ids]) / west_occupancy\n\nc_lo = -1.5\nc_hi = 1.5\n\n# Plot change maps filtered by direction\nplt.subplot(3,3,2)\nplt.title('Unfolded Pixel Change Map')\nplt.imshow(west_pix_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,4)\nplt.imshow(south_pix_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,5)\nplt.imshow(pixel_change_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,6)\nplt.imshow(north_pix_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,8)\nplt.imshow(east_pix_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.show()\n\nplt.subplot(3,3,2)\nplt.title('Unfolded Rate Change Map')\nplt.imshow(west_rat_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,4)\nplt.imshow(south_rat_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,5)\nplt.imshow(rate_change_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,6)\nplt.imshow(north_rat_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.subplot(3,3,8)\nplt.imshow(east_rat_map.T, origin='upper', cmap=cmap)\nplt.clim([c_lo,c_hi])\nplt.axis('off')\nplt.show()", "\nfrom copy import deepcopy\n\nimport numpy as np\nfrom scipy import ndimage\nimport cv2 as cv\nfrom skimage.measure import regionprops\n\nfrom barrylab_ephys_analysis.spatial.similarity import spatial_correlation\n\n\ndef compute_field_stability(field_ratemap, spike_rates_1, spike_rates_2,\n min_included_value, min_bins):\n \"\"\"Returns the pearson correlation of two ratemaps at location of field ratemap.\n Excludes all bins that are numpy.nan or < 0 in field ratemap.\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins) array with np.nan outside field\n :param spike_rates_1: shape (n_ybins, n_xbins) array\n :param spike_rates_2: shape (n_ybins, n_xbins) array\n :param min_included_value: minimum value in spike_rates_1 and spike_rates_2 for bin to be included\n :param min_bins: minimum number of bins that must remain to compute correlation, else returns numpy.nan\n :return: rho\n :rtype: float\n \"\"\"\n field_ratemap = field_ratemap.copy()\n field_ratemap[np.isnan(field_ratemap)] = 0\n return spatial_correlation(spike_rates_1, spike_rates_2,\n min_included_value=min_included_value,\n mask=(field_ratemap > 0),\n min_bins=min_bins)[0]\n\n\ndef primary_filter(ratemap, min_area_bins=0, min_peak_value=0):\n \"\"\"Returns True if ratemap passes filter criteria, False otherwise\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins) array with np.nan outside field\n :param int min_area_bins: number of non-zero bins in ratemap required to pass\n :param float min_peak_value: minimum required maximum value in ratemap to pass\n :return: pass\n :rtype: bool\n \"\"\"\n if np.count_nonzero(ratemap) < min_area_bins:\n return False\n if np.nanmax(ratemap) < min_peak_value:\n return False\n\n return True\n\n\ndef secondary_filter(ratemap, max_area_bins, stability_ratemaps,\n min_stability, stability_kwargs):\n \"\"\"Returns True if ratemap passes filter criteria, False otherwise\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins) array with np.nan outside field\n :param int max_area_bins: maximum number of bins greater than 0 in ratemap allowed to pass\n :param tuple stability_ratemaps: tuple with two ratemaps that are used for computing the stability\n of a field_ratemap after masking them with the non-numpy.nan elements in field_ratemap\n :param float min_stability: minimum required stability in stability_ratemaps to pass\n :param dict stability_kwargs: passed on to :py:func:`compute_field_stability`\n :return: pass\n :rtype: bool\n \"\"\"\n if np.count_nonzero(ratemap) > max_area_bins:\n return False\n\n if 'min_included_value' in stability_kwargs and stability_kwargs['min_included_value'] <= 0:\n raise Exception('This module uses 0 values as indication of outside of bin areas.\\n'\n + 'Therefore, min_included_value must be above 0 for stability computation,\\n'\n + 'but is currently {}'.format(stability_kwargs['min_included_value']))\n stability = compute_field_stability(ratemap, stability_ratemaps[0],\n stability_ratemaps[1], **stability_kwargs)\n if np.isnan(stability) or stability < min_stability:\n return False\n\n return True\n\n\ndef create_field_ratemap(ratemap, field_idx):\n \"\"\"Returns a copy of input `ratemap`, where fields not True in `field_idx` are set to `0`.\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins)\n :param numpy.ndarray field_idx: boolean array same shape as ratemap, specifying which elements\n belong to the field.\n :return: field_ratemap\n :rtype: numpy.ndarray\n \"\"\"\n field_ratemap = ratemap.copy()\n field_ratemap[~field_idx] = 0\n\n return field_ratemap\n\n\ndef get_field_map(ratemap):\n \"\"\"Returns the contiguous region map as identified with :py:func:`scipy.ndimage.label`.\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins)\n :return: same as input but integer identifiers marking which elements belong to which proximal group\n :rtype: numpy.ndarray\n \"\"\"\n return ndimage.label(ratemap > 0)[0]\n\n\ndef get_filtered_subfield_ratemaps(ratemap, primary_filter_kwargs):\n \"\"\"Returns a list containing a copy of ratemap for each field that passes the primary filter\n :py:func:`spatial.fields.primary_filter` where values outside the field are set `0`.\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins)\n :param dict primary_filter_kwargs: see :py:func:`spatial.field.primary_filter` keyword arguments.\n filter_kwargs is passed on to that function as `**filter_kwargs` after `ratemap` argument.\n :return: field_ratemaps\n :rtype: list\n \"\"\"\n field_map = get_field_map(ratemap)\n\n field_nrs = np.unique(field_map)[1:] # ignores the 0 background field\n\n # If no fields were detected, return no fields\n if len(field_nrs) == 0:\n return []\n\n field_ratemaps = []\n for field_nr in field_nrs:\n field_ratemap = create_field_ratemap(ratemap, field_map == field_nr)\n if primary_filter(field_ratemap, **primary_filter_kwargs):\n field_ratemaps.append(field_ratemap)\n\n return field_ratemaps\n\n\ndef detect_field_candidates(ratemap, base_threshold, threshold_step, primary_filter_kwargs):\n \"\"\"Returns a list of field_candidates that passed primary_filter.\n\n The returned field_candidates list is a nested list with the following structure:\n - Each element in list contains two elements.\n - The first element is the origin index within field_candidates. This is None for first subfields,\n but int after.\n - The second element is a list of ratemaps with increasingly higher threshold, that all\n have only a single continugous region. The final element in the ratemap list is None,\n if no further subfields were found with the next threshold (none passed the primary_filter).\n - If more than one subfield is found, these are separately appended to field_candidates list following\n the same structure and using the origin index of the previous level where they were detected.\n\n - The field_candidates list is populated in an iterative fashion. Each iteration the ratemap threshold is increase\n by threshold_step.\n - If a single new field passes primary_filter, it is appended to the list of ratemaps for that level and\n procedure is repeated.\n - If no new fields pass primary_filter, the ratemap list is ended with None. This causes the loop to start\n the procedure on the next level in the field_candidates list.\n - New levels are added to the field_candidates list each time two or more fields are detected and pass the\n primary_filter. In that case, after the new fields are appended to field_candidates list,\n the loop moves on to next level.\n - As a result the loop extracts all possible field_candidates and also forms links between them.\n This allows working backwards through this list along the order of inheritance (field and subfield links).\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins) ratemap. Any numpy.nan elements should\n be replaced with zeros before passing ratemap to this function\n :param float base_threshold: baseline threshold level from which to start detecting fields\n :param float threshold_step: threshold shift at each iteration\n :param dict primary_filter_kwargs: see :py:func:`spatial.field.primary_filter` keyword arguments.\n filter_kwargs is passed on to that function as `**filter_kwargs` after `ratemap` argument.\n :return: field_candidates\n :rtype: list\n \"\"\"\n\n # Use a copy of original input ratemap, threshold and threshold the ratemap.\n ratemap = ratemap.copy()\n current_threshold = deepcopy(base_threshold)\n ratemap[ratemap < current_threshold] = 0\n\n # Find all subfields in the ratemap at baseline threshold\n subfields = get_filtered_subfield_ratemaps(ratemap, primary_filter_kwargs)\n\n # If no subfields were found, return an empty list\n if len(subfields) == 0:\n return []\n\n # Create fields list with the initial subfields\n field_candidates = []\n for subfield in subfields:\n field_candidates.append((None, [subfield]))\n\n current_level = 0\n\n # Continuoue the loop until the last level ratemap list ends with None\n while not (field_candidates[-1][1][-1] is None):\n\n # If current level ratemaplist ends with None, move to next level\n if field_candidates[current_level][1][-1] is None:\n current_level += 1\n\n # Increase current_threshold and create a copy of current_ratemap with the current_threshold\n current_threshold += threshold_step\n current_ratemap = field_candidates[current_level][1][-1].copy()\n current_ratemap[current_ratemap < current_threshold] = 0\n\n # Find subfields for current level\n subfields = get_filtered_subfield_ratemaps(current_ratemap, primary_filter_kwargs)\n\n if len(subfields) == 0:\n # If no subfields were found, end the current level ratemap list with None\n field_candidates[current_level][1].append(None)\n\n elif len(subfields) == 1:\n # If a single field was found, append to current level ratemap list\n field_candidates[current_level][1].append(subfields[0])\n\n else:\n # If more than one field was found, append these to field_candidates list\n for subfield in subfields:\n field_candidates.append((current_level, [subfield]))\n # If more than one field was found, move to next level\n current_level += 1\n\n return field_candidates\n\n\ndef extract_fields_from_field_candidates(field_candidates, secondary_filter_kwargs):\n \"\"\"Returns the field_ratemap with lowest threshold of each field_candidate that\n passes the :py:func:`secondary_filter`.\n\n Iterates through field_candidates in reverse order of detection in :py:func:`detect_field_candidates`.\n Ignores any field_candiate elements that were the origin of sub-fields that pass secondary_filter.\n\n :param list field_candidates: output from :py:func:`detect_field_candidates`\n :param dict secondary_filter_kwargs: see :py:func:`spatial.field.secondary_filter` keyword arguments.\n filter_kwargs is passed on to that function as `**filter_kwargs` after `ratemap` argument.\n :return: field_ratemaps\n :rtype: list\n \"\"\"\n field_ratemap_dicts = []\n\n # Loop through levels of the field_candidates list starting from the last\n for current_level in range(len(field_candidates))[::-1]:\n\n # Get the field_candidate element for the current_level\n field_candidate = field_candidates[current_level]\n\n # Find out if current level field_candidate has any sub-fields already passed the secondary_filter\n n_subfields = 0\n for field_ratemap_dict in field_ratemap_dicts:\n if field_ratemap_dict['origin'] == current_level:\n n_subfields += 1\n\n # If more than one subfield has been identified for this field_candidate,\n # pass origin of this field_candidate to detected subfields and skip processing this field_candidate.\n if n_subfields > 1:\n for field_ratemap_dict in field_ratemap_dicts:\n if field_ratemap_dict['origin'] == current_level:\n field_ratemap_dict['origin'] = field_candidate[0]\n continue\n\n field_ratemap = None\n\n # Loop through the ratemaps of this field_candiate\n for field_candidate_ratemap in field_candidate[1][::-1]:\n\n # field_candidate_ratemap lists can end in None. Ignore these elements.\n if field_candidate_ratemap is None:\n continue\n\n if secondary_filter(field_candidate_ratemap, **secondary_filter_kwargs):\n # If a ratemap passes the secondary_filter, overwrite the field_ratemap\n # This way final field_ratemap is the one detected with lowest threshold\n # but still passes the secondary_filter.\n field_ratemap = field_candidate_ratemap\n\n if field_ratemap is None:\n\n if n_subfields == 1:\n # If no field_ratemap passed the secondary_filter fo this field_candidate,\n # but this field_candidate had one subfield passing through the filter earlier\n # assign the origin of that subfield to be the origin of current field_candidate.\n subfield_index = [field_ratemap_dict['origin']\n for field_ratemap_dict in field_ratemap_dicts].index(current_level)\n field_ratemap_dicts[subfield_index]['origin'] = field_candidate[0]\n\n else:\n\n # If a field_ratemap did pass the secondary_filter, append it to field_ratemap_dicts\n field_ratemap_dicts.append({'ratemap': field_ratemap,\n 'origin': field_candidate[0]})\n\n if n_subfields == 1:\n # Remove the single subfield of the current field_candidate from field_ratemap_dicts list\n subfield_index = [field_ratemap_dict['origin']\n for field_ratemap_dict in field_ratemap_dicts].index(current_level)\n del field_ratemap_dicts[subfield_index]\n\n field_ratemaps = [field_ratemap_dict['ratemap'] for field_ratemap_dict in field_ratemap_dicts\n if 'ratemap' in field_ratemap_dict]\n\n return field_ratemaps\n\n\ndef detect_fields(ratemap, stability_ratemaps, base_threshold, threshold_step,\n primary_filter_kwargs, secondary_filter_kwargs):\n \"\"\"Returns a list of copies of input `ratemap` with every value except those in field\n replaced by `numpy.nan`.\n\n :param numpy.ndarray ratemap: shape (n_ybins, n_xbins) ratemap for fields to be detected.\n Values to be ignored should be set to numpy.nan.\n :param tuple stability_ratemaps: tuple with two ratemaps that are used for computing the stability\n of a field_ratemap after masking them with the non-numpy.nan elements in field_ratemap\n :param float base_threshold: values below this are set to numpy.nan and ignored\n :param float threshold_step: the step in ratemap values for iterative detection of fields.\n :param dict primary_filter_kwargs: see :py:func:`spatial.field.primary_filter` keyword arguments.\n filter_kwargs is passed on to that function as `**filter_kwargs` after `ratemap` argument.\n :param dict secondary_filter_kwargs: see :py:func:`spatial.field.secondary_filter` keyword arguments.\n `'max_relative_bins'` element is replaced with `'max_area_bins'` computed based on the `ratemap`.\n secondary_filter_kwargs is then passed on to that function as `**filter_kwargs` after `ratemap` argument.\n :return: field_ratemaps list of ratemaps where values outside field are numpy.nan\n :rtype: list\n \"\"\"\n # Add stability_ratemaps and max_area_bins to a copy of secondary_filter_kwargs\n secondary_filter_kwargs = deepcopy(secondary_filter_kwargs)\n secondary_filter_kwargs['stability_ratemaps'] = stability_ratemaps\n secondary_filter_kwargs['max_area_bins'] = \\\n np.sum(~np.isnan(ratemap)) * secondary_filter_kwargs.pop('max_relative_bins')\n\n # Ensure original ratemap is not modified\n ratemap = ratemap.copy()\n\n # Ensure ratemap is in float dtype to support nans that are required in final output format\n if not isinstance(ratemap.dtype, np.floating):\n ratemap = ratemap.astype(np.float64)\n\n # Set numpy.nan values to 0 for compatibility with field detection methods.\n ratemap[np.isnan(ratemap)] = 0\n\n # Detect field candidates and extract those that pass all filters\n field_candidates = detect_field_candidates(ratemap, base_threshold, threshold_step, primary_filter_kwargs)\n field_ratemaps = extract_fields_from_field_candidates(field_candidates, secondary_filter_kwargs)\n\n # Set field_ratemap values of 0 to numpy.nan to indicate outside of field areas\n for i, field_ratemap in enumerate(field_ratemaps):\n field_ratemaps[i][field_ratemap == 0] = np.nan\n\n return field_ratemaps\n\n\ndef get_field_regionprops(field_ratemap, data_x_values=None, data_y_values=None,\n orientation_x_axis_0_to_pi=True):\n \"\"\"Returns output from :py:func:`skimage.measure.regionprops` for the boolean field map.\n\n Note, if data_x_values and data_y_values (both or neither must be provided), these are used\n to estimate corresponding centroid_x, centroid_y, minor_axis and major_axis values.\n\n Note, data_x_values and data_y_values must have equal and constant spacing in values,\n as the correction on minor_axis and major_axis length are based on this assumption.\n\n :param numpy.ndarray field_ratemap: shape (n_ybins, n_xbins) ratemap with numpy.nan values\n outside the field.\n :param numpy.ndarray data_x_values: if provided, to estimate position and axes length values\n :param numpy.ndarray data_y_values: if provided, to estimate position and axes length values\n :param bool orientation_x_axis_0_to_pi: if True (default), orientation value is set to range from\n 0 to pi, increasing clock-wise from parallel to x-axis.\n :return: dictionary with selection of field properties returned by :py:func:`skimage.measure.regionprops`\n :rtype: dict\n \"\"\"\n if (data_x_values is None) != (data_y_values is None):\n raise ValueError('data_x_values and data_y_values must both be provided or neither.')\n\n if not (data_x_values is None):\n x_offset = data_x_values[0]\n y_offset = data_y_values[0]\n pixel_edge_length = data_x_values[1] - data_x_values[0]\n else:\n x_offset = None\n y_offset = None\n pixel_edge_length = None\n\n out = regionprops(np.uint8(~np.isnan(field_ratemap)), coordinates='rc')[0]\n return {'area': out.area,\n 'centroid_x': (out.centroid[1] if (data_x_values is None)\n else out.centroid[1] * pixel_edge_length + x_offset),\n 'centroid_y': (out.centroid[0] if (data_y_values is None)\n else out.centroid[0] * pixel_edge_length + y_offset),\n 'eccentricity': out.eccentricity,\n 'minor_axis': (out.minor_axis_length if pixel_edge_length is None\n else out.minor_axis_length * pixel_edge_length),\n 'major_axis': (out.major_axis_length if pixel_edge_length is None\n else out.major_axis_length * pixel_edge_length),\n 'orientation': ((-out.orientation + np.pi / 2.) if orientation_x_axis_0_to_pi\n else out.orientation)}\n\n\ndef compute_field_contour(field_ratemap, flipud=True):\n \"\"\"Returns contour points of the field in the field_ratemap.\n\n Assumes input has only one contiguous region of values above 0 and not `numpy.nan`,\n\n :param numpy.ndarray field_ratemap: shape (n_ybins, n_xbins) ratemap with numpy.nan values\n outside the field.\n :return: contours list of contour points\n :param bool flipud: if True (default), the field_ratemap array is flipped prior to extracting\n the contour. This yields correct contour point values relative to field_ratemap array indices.\n :rtype: list\n \"\"\"\n # The ratemap needs to be flipped on the vertical axis, because OpenCV starts counting\n # y-axis positions from bottom edge, but our analysis assumes position values are counted\n # ascending from the top edge of the ratemap array.\n if flipud:\n field_ratemap = np.flipud(field_ratemap.copy())\n\n # Convert input to binary\n field_ratemap[np.isnan(field_ratemap)] = 0\n field_binary_map = np.uint8(field_ratemap > 0)\n\n # Only keep the first contour from output list, as input should only have one region\n contour = cv.findContours(field_binary_map, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)[0][0]\n\n return contour\n\n\ndef compute_field_ellipse(field_ratemap, flipud=False):\n \"\"\"\n\n :param numpy.ndarray field_ratemap: shape (n_ybins, n_xbins) ratemap with numpy.nan values\n outside the field.\n :param bool flipud: if False (default), ratemap is not flipped along first dimension for\n detecting contour prior to ellipse fitting. This yields correct ellipse coordinates\n relative to field_ratemap array indices.\n :return:\n \"\"\"\n\n contour = compute_field_contour(field_ratemap, flipud=flipud)\n\n (x, y), (MA, ma), angle = cv.fitEllipse(contour)\n\n return {'x': x, 'y': y, 'major_axis_width': MA, 'minor_axis_width': ma, 'angle': angle}\n", "\nimport numpy as np\n\nfrom barrylab_ephys_analysis.blea_utils import smooth_signal_with_gaussian\nfrom barrylab_ephys_analysis.lfp.processing import bandpass_filter, hilbert_fast\nfrom barrylab_ephys_analysis.base import AnalogSignal\n\n\nclass FrequencyBandAmplitude(AnalogSignal):\n \"\"\"\n Computes frequency band amplitude for a recording and provides convenient access based on\n :py:class:`barrylab_ephys_analysis.base.AnalogSignal`.\n\n If existing data with same name is found in recording.analysis['analog_signals'],\n then that data is used instead, if it matches the input parameters.\n \"\"\"\n\n def __init__(self, *args, highpass_frequency=None, lowpass_frequency=None,\n filter_order=None, temporal_smoothing_sigma=None, common_average=False,\n channel_group_tetrodes=None, verbose=False, **kwargs):\n \"\"\"\n :param highpass_frequency: Hz (must be provided)\n :param lowpass_frequency: Hz (must be provided)\n :param int filter_order: (must be provided)\n :param float temporal_smoothing_sigma: temporal smoothing gaussian stdev in seconds (must be provided)\n :param bool common_average: specifies if common average is compute for each channel group before processing.\n Default is False, no common averaging.\n :param dict channel_group_tetrodes: {channel_group_A: 5, channel_group_B: [6, 8]} specifies that for\n channel_group_A, only tetrode 5 is used and for channel_group_B, tetrodes 6 and 8 are used.\n Default is to use all tetrodes on all channel groups. This must be provided for all groups or none.\n :param bool verbose: if True, prints progress. Default is False.\n \"\"\"\n self._params = {\n 'highpass_frequency': np.array(highpass_frequency),\n 'lowpass_frequency': np.array(lowpass_frequency),\n 'filter_order': np.array(filter_order),\n 'temporal_smoothing_sigma': np.array(temporal_smoothing_sigma),\n 'common_average': np.array(common_average),\n 'channel_group_tetrodes': ({key: np.array(value) for key, value in channel_group_tetrodes.items()}\n if isinstance(channel_group_tetrodes, dict) else np.array(np.nan))\n }\n self.verbose = verbose\n super(FrequencyBandAmplitude, self).__init__(*args, **kwargs)\n\n @staticmethod\n def compute_frequency_band_amplitude(continuous, sampling_rate, highpass_frequency,\n lowpass_frequency, filter_order):\n \"\"\"Returns amplitude envelope of a signal in 1-D array\n\n :param numpy.ndarray continuous: shape (N,)\n :param sampling_rate: Hz\n :param highpass_frequency: Hz\n :param lowpass_frequency: Hz\n :param int filter_order:\n :return: amplitude_envelope\n :rtype: numpy.ndarray\n \"\"\"\n filtered_signal = bandpass_filter(continuous, sampling_rate=sampling_rate,\n lowpass_frequency=lowpass_frequency,\n highpass_frequency=highpass_frequency,\n filter_order=filter_order)\n return np.abs(hilbert_fast(filtered_signal))\n\n def compute_values_for_continuous_array(self, continuous):\n \"\"\"Computes frequency band amplitude for along first dimension for all columns.\n\n This can be overwritten by a subclass to provide a different value for continuous array,\n but must return an array of same shape as it receives.\n\n Note! The output from this function is averaged along the second dimension, using np.mean(x, axis=1).\n\n :param numpy.ndarray continuous: shape (n_samples, n_channels)\n :return: value_array shape (n_samples, n_channels)\n :rtype: numpy.ndarray\n \"\"\"\n return np.apply_along_axis(\n FrequencyBandAmplitude.compute_frequency_band_amplitude, 0, continuous,\n self.recording.continuous['sampling_rate'],\n highpass_frequency=self._params['highpass_frequency'],\n lowpass_frequency=self._params['lowpass_frequency'],\n filter_order=self._params['filter_order']\n )\n\n @staticmethod\n def smooth_signal(signal, temporal_smoothing_sigma, sampling_rate):\n return smooth_signal_with_gaussian(signal, temporal_smoothing_sigma * sampling_rate)\n\n def compute_for_channel_group(self, channel_group):\n\n if isinstance(self._params['channel_group_tetrodes'], dict):\n tetrode_nrs = self._params['channel_group_tetrodes'][channel_group]\n else:\n tetrode_nrs = self.recording.channel_map[channel_group]['tetrode_nrs']\n\n if self._params['common_average'] and len(tetrode_nrs) > 1:\n\n common_average = np.mean(self.recording.continuous['continuous'][:, tetrode_nrs], axis=1)\n continuous = np.apply_along_axis(lambda x: x - common_average, 0,\n self.recording.continuous['continuous'][:, tetrode_nrs])\n else:\n\n continuous = self.recording.continuous['continuous'][:, tetrode_nrs]\n\n if len(continuous.shape) == 1:\n continuous = continuous[:, np.newaxis]\n\n amplitude = np.mean(self.compute_values_for_continuous_array(continuous), axis=1)\n\n if (not (self._params['temporal_smoothing_sigma'] is None)\n and self._params['temporal_smoothing_sigma'] != 0):\n amplitude = self.smooth_signal(amplitude, self._params['temporal_smoothing_sigma'],\n self.recording.continuous['sampling_rate'])\n\n return amplitude\n\n def compute(self, recompute=False):\n\n # If available data params match input params, skip recomputing, unless requested\n if not recompute and not (self.data is None):\n params_match = []\n for key, item in self._params.items():\n if key == 'channel_group_tetrodes' and not isinstance(item, dict):\n continue\n params_match.append(self.data['params'][key] == item)\n if all(params_match):\n if self.verbose:\n print('Exisiting {} params match input, skipping computation.'.format(self.name))\n return\n\n if self.verbose:\n print('Computing {}'.format(self.name))\n\n signals = []\n labels = []\n\n for channel_group in self.recording.channel_map:\n signals.append(self.compute_for_channel_group(channel_group)[:, None])\n labels.append(channel_group)\n\n self.data = {'first_timestamp': np.array(self.recording.continuous['timestamps'][0]),\n 'sampling_rate': np.array(self.recording.continuous['sampling_rate']),\n 'signal': np.concatenate(signals, axis=1),\n 'channel_labels': labels,\n 'params': self._params}\n\n\nclass FrequencyBandFrequency(FrequencyBandAmplitude):\n \"\"\"\n Computes frequency band instantaneous frequency for a recording and provides convenient access based on\n :py:class:`FrequencyBandAmplitude` and :py:class:`barrylab_ephys_analysis.base.AnalogSignal`.\n \"\"\"\n\n @staticmethod\n def compute_frequency_band_frequency(continuous, sampling_rate, highpass_frequency,\n lowpass_frequency, filter_order):\n \"\"\"Returns instantaneous frequency of a signal in 1-D array.\n\n Note! Due to the nature of computing instantaneous frequency, the values are\n shifted forward by half a sample.\n\n :param numpy.ndarray continuous: shape (N,)\n :param sampling_rate: Hz\n :param highpass_frequency: Hz\n :param lowpass_frequency: Hz\n :param int filter_order:\n :return: instantaneous_frequency shape (N,)\n :rtype: numpy.ndarray\n \"\"\"\n filtered_signal = bandpass_filter(continuous, sampling_rate=sampling_rate,\n lowpass_frequency=lowpass_frequency,\n highpass_frequency=highpass_frequency,\n filter_order=filter_order)\n instantaneous_phase = np.unwrap(np.angle(hilbert_fast(filtered_signal)))\n instantaneous_frequency = (np.diff(instantaneous_phase) / (2.0 * np.pi) * sampling_rate)\n instantaneous_frequency = np.concatenate((instantaneous_frequency[:1], instantaneous_frequency))\n return instantaneous_frequency\n\n def compute_values_for_continuous_array(self, continuous):\n \"\"\"Computes instantaneous frequency along first dimension for all columns.\n\n :param numpy.ndarray continuous: shape (n_samples, n_channels)\n :return: value_array shape (n_samples, n_channels)\n :rtype: numpy.ndarray\n \"\"\"\n return np.apply_along_axis(\n FrequencyBandFrequency.compute_frequency_band_frequency, 0, continuous,\n self.recording.continuous['sampling_rate'],\n highpass_frequency=self._params['highpass_frequency'],\n lowpass_frequency=self._params['lowpass_frequency'],\n filter_order=self._params['filter_order']\n )\n\n\nclass FrequencyBandPhase(FrequencyBandAmplitude):\n \"\"\"\n Computes frequency band instantaneous phase for a recording and provides convenient access based on\n :py:class:`FrequencyBandAmplitude` and :py:class:`barrylab_ephys_analysis.base.AnalogSignal`.\n\n Phase is computed and stored in radians in unwrapped form.\n\n .. warning::\n\n If temporal_smoothing_sigma argument above 0 is provided, then phase is unwrapped using\n :py:func:`numpy.unwrap` and wrapped again using :py:func:`FrequencyBandPhase.wrap_phase_to_range_between_pi`.\n It is important that the sampling rate of the signal is sufficiently high for this method to work.\n\n \"\"\"\n\n @staticmethod\n def wrap_phase_to_range_between_pi(signal):\n \"\"\"Returns input signal wrapped to range between -pi to pi\n\n :param numpy.ndarray signal:\n :return: wrapped_signal\n \"\"\"\n return np.mod(signal + np.pi, 2 * np.pi) - np.pi\n\n @staticmethod\n def compute_frequency_band_phase(continuous, sampling_rate, highpass_frequency,\n lowpass_frequency, filter_order):\n \"\"\"Returns instantaneous phase of a signal in 1-D array in unwrapped form.\n\n :param numpy.ndarray continuous: shape (N,)\n :param sampling_rate: Hz\n :param highpass_frequency: Hz\n :param lowpass_frequency: Hz\n :param int filter_order:\n :return: instantaneous_phase shape (N,)\n :rtype: numpy.ndarray\n \"\"\"\n filtered_signal = bandpass_filter(continuous, sampling_rate=sampling_rate,\n lowpass_frequency=lowpass_frequency,\n highpass_frequency=highpass_frequency,\n filter_order=filter_order)\n instantaneous_phase = np.angle(hilbert_fast(filtered_signal))\n return instantaneous_phase\n\n def compute_values_for_continuous_array(self, continuous):\n \"\"\"Computes instantaneous phase along first dimension for all columns.\n\n :param numpy.ndarray continuous: shape (n_samples, n_channels)\n :return: value_array shape (n_samples, n_channels)\n :rtype: numpy.ndarray\n \"\"\"\n return np.apply_along_axis(\n FrequencyBandPhase.compute_frequency_band_phase, 0, continuous,\n self.recording.continuous['sampling_rate'],\n highpass_frequency=self._params['highpass_frequency'],\n lowpass_frequency=self._params['lowpass_frequency'],\n filter_order=self._params['filter_order']\n )\n\n @staticmethod\n def smooth_signal(signal, temporal_smoothing_sigma, sampling_rate):\n return FrequencyBandPhase.wrap_phase_to_range_between_pi(\n smooth_signal_with_gaussian(np.unwrap(signal, axis=0), temporal_smoothing_sigma * sampling_rate)\n )\n\n\nclass ThetaDeltaRatio(AnalogSignal):\n\n def __init__(self, *args, theta_band_amplitude=None, delta_band_amplitude=None,\n speed=None, mean_ratio_min_speed=None, **kwargs):\n \"\"\"\n :param theta_band_amplitude: :py:class:`FrequencyBandAmplitude` instantiated for theta frequency band\n :param delta_band_amplitude: :py:class:`FrequencyBandAmplitude` instantiated for delta frequency band\n :param speed: :py:class:`barrylab_ephys_analysis.base.AnalogSignal` for animal speed\n :param float mean_ratio_min_speed: minimum animal speed threshold for calculating mean theta/delta ratio\n \"\"\"\n self._theta_band_amplitude = theta_band_amplitude\n self._delta_band_amplitude = delta_band_amplitude\n self._speed = speed\n self._params = {'mean_ratio_min_speed': np.array(mean_ratio_min_speed)}\n super(ThetaDeltaRatio, self).__init__(*args, **kwargs)\n\n def compute(self, recompute=False):\n\n # If available data params match input params, skip recomputing, unless requested\n if not recompute and not (self.data is None):\n if all([self.data['params'][key] == item for key, item in self._params.items()]):\n return\n\n print('Computing ThetaDeltaRatio')\n\n # Compute mean np.log(ratio) of theta/delta amplitude during running epochs\n running_epoch_timestamps = self._speed.get_epoch_timestamps_function_of_signal_true(\n lambda x: np.array(x > self._params['mean_ratio_min_speed']).squeeze()\n )\n running_theta_amplitude = np.mean(\n np.concatenate(\n [self._theta_band_amplitude.get_values_between_timestamps(*ets, allow_clipping=True)[0]\n for ets in running_epoch_timestamps]\n ),\n axis=1\n )\n running_delta_amplitude = np.mean(\n np.concatenate(\n [self._delta_band_amplitude.get_values_between_timestamps(*ets, allow_clipping=True)[0]\n for ets in running_epoch_timestamps]\n ),\n axis=1\n )\n running_mean_ratio = np.mean(np.log(running_theta_amplitude / running_delta_amplitude))\n\n # Get theta/delta ratio with timestamps\n ratio = np.log(np.mean(self._theta_band_amplitude.data['signal'], axis=1)\n / np.mean(self._delta_band_amplitude.data['signal'], axis=1))\n\n self.data = {'first_timestamp': self._theta_band_amplitude.data['first_timestamp'],\n 'sampling_rate': self._theta_band_amplitude.data['sampling_rate'],\n 'signal': ratio[:, None],\n 'channel_labels': [''],\n 'params': self._params,\n 'running_mean_ratio': np.array(running_mean_ratio)}\n" ]
[ [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.title", "matplotlib.pyplot.clim", "scipy.stats.pearsonr", "numpy.vstack", "matplotlib.pyplot.get_cmap", "numpy.degrees", "numpy.append", "matplotlib.pyplot.subplot", "numpy.std", "numpy.diff", "numpy.mean", "matplotlib.pyplot.axis", "numpy.load", "pandas.read_pickle", "matplotlib.pyplot.show" ], [ "numpy.nanmax", "numpy.unique", "numpy.isnan", "numpy.uint8", "scipy.ndimage.label", "numpy.count_nonzero" ], [ "numpy.log", "numpy.concatenate", "numpy.unwrap", "numpy.apply_along_axis", "numpy.mean", "numpy.diff", "numpy.mod", "numpy.array" ] ]
[ { "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": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "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": [] } ]
alik-git/mbrl-lib
[ "b364f8e64ca71ebd18147fe8cdbd3068b74e1f1e", "b364f8e64ca71ebd18147fe8cdbd3068b74e1f1e" ]
[ "mbrl/examples/main.py", "mbrl/models/planet_legacy.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\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.\nfrom typing import Iterable\nimport hydra\nimport numpy as np\nimport omegaconf\nimport torch\n\nimport mbrl.algorithms.mbpo as mbpo\nimport mbrl.algorithms.pets as pets\nimport mbrl.algorithms.planet as planet\nimport mbrl.algorithms.dreamer as dreamer #added April 2022 for project\nimport mbrl.util.env\n\nimport pandas as pd\nfrom collections import Iterable\n\nimport wandb\n\ndef flatten_config(cfg, curr_nested_key):\n \"\"\"The nested config file provided by Hydra cannot be parsed by wandb. This recursive function flattens the config file, separating the nested keys and their parents via an underscore. Allows for easier configuration using wandb.\n\n Args:\n cfg (Hydra config): The nested config file used by Hydra.\n curr_nested_key (str): The current parent key (used for recursive calls).\n\n Returns:\n (dict): A flatt configuration dictionary.\n \"\"\" \n \n flat_cfg = {}\n\n for curr_key in cfg.keys():\n\n # deal with missing values\n try:\n curr_item = cfg[curr_key]\n except Exception as e:\n curr_item = 'NA'\n\n # deal with lists\n if type(curr_item) == list or type(curr_item) == omegaconf.listconfig.ListConfig:\n for nested_idx, nested_item in enumerate(curr_item):\n list_nested_key = f\"{curr_nested_key}_{curr_key}_{nested_idx}\"\n flat_cfg[list_nested_key] = nested_item\n \n # check if item is also a config\n # recurse\n elif isinstance(curr_item, Iterable) and type(curr_item) != str:\n flat_cfg.update(flatten_config(curr_item, f\"{curr_nested_key}_{curr_key}\"))\n\n # otherwise just add to return dict\n else:\n flat_cfg[f\"{curr_nested_key}_{curr_key}\"] = curr_item\n\n return flat_cfg\n\[email protected](config_path=\"conf\", config_name=\"main\")\ndef run(cfg: omegaconf.DictConfig):\n env, term_fn, reward_fn = mbrl.util.env.EnvHandler.make_env(cfg)\n \n for config_item in cfg:\n wandb.config[config_item] = cfg[config_item]\n \n flat_cfg = flatten_config(cfg, \"\")\n for config_item in flat_cfg:\n wandb.config[config_item] = flat_cfg[config_item]\n \n np.random.seed(cfg.seed)\n torch.manual_seed(cfg.seed)\n if cfg.algorithm.name == \"pets\":\n return pets.train(env, term_fn, reward_fn, cfg)\n if cfg.algorithm.name == \"mbpo\":\n test_env, *_ = mbrl.util.env.EnvHandler.make_env(cfg)\n return mbpo.train(env, test_env, term_fn, cfg)\n if cfg.algorithm.name == \"planet\":\n return planet.train(env, cfg)\n if cfg.algorithm.name == \"dreamer\": #added for project\n return dreamer.train(env, cfg)\n\n\nif __name__ == \"__main__\":\n wandb.init(project=\"MBRL_Duckyt\", entity=\"mbrl_ducky\", monitor_gym=True)\n run()\n", "import torch\nimport numpy as np\nfrom typing import Tuple, Any, Union, Optional, Dict\nTensorType = Any\n\nclass DMControlSuiteEnv:\n\n def __init__(self, \n name: str, \n max_episode_length: int = 1000,\n action_repeat:int = 2,\n size: Tuple[int] = (64, 64),\n camera: Optional[Any] = None,\n ):\n domain, task = name.split('_', 1)\n if domain == 'cup':\n domain = 'ball_in_cup'\n if isinstance(domain, str):\n from dm_control import suite\n self._env = suite.load(domain, task)\n else:\n assert task is None\n self._env = domain()\n self._size = size\n if camera is None:\n camera = dict(quadruped=2).get(domain, 0)\n self._camera = camera\n self._step = 0\n self._max_episode_length = max_episode_length\n self._action_repeat = action_repeat\n \n @property\n def observation_space(self):\n spaces = {}\n for key, value in self._env.observation_spec().items():\n spaces[key] = gym.spaces.Box(\n -np.inf, np.inf, value.shape, dtype=np.float32)\n spaces['image'] = gym.spaces.Box(\n 0, 255, self._size + (3,), dtype=np.uint8)\n return gym.spaces.Dict(spaces)\n\n @property\n def action_space(self):\n spec = self._env.action_spec()\n return gym.spaces.Box(spec.minimum, spec.maximum, dtype=np.float32)\n\n def step(self, action):\n reward = 0\n obs = None\n for k in range(self._action_repeat):\n time_step = self._env.step(action)\n self._step += 1\n obs = dict(time_step.observation)\n obs['image'] = self.render()\n reward += time_step.reward or 0\n done = time_step.last() or self._step == self._max_episode_length\n if done:\n break\n info = {'discount': np.array(time_step.discount, np.float32)}\n return obs[\"image\"], reward, done, info\n\n def reset(self):\n time_step = self._env.reset()\n self._step = 0\n obs = dict(time_step.observation)\n obs['image'] = self.render()\n return obs[\"image\"]\n\n def render(self, *args, **kwargs):\n if kwargs.get('mode', 'rgb_array') != 'rgb_array':\n raise ValueError(\"Only render mode 'rgb_array' is supported.\")\n return self._env.physics.render(*self._size, camera_id=self._camera)\n\nclass Episode(object):\n \"\"\" Episode Class which contains the related\n attributes of an environment episode in the\n the format similar to queue\"\"\"\n \n def __init__(self,\n obs:TensorType,\n action_space: int = 1,\n action_repeat: int = 2) -> None:\n \"\"\"Initializes a list of all episode attributes\"\"\"\n self.action_space = action_space\n self.action_repeat = action_repeat\n obs = torch.FloatTensor(np.ascontiguousarray(obs.transpose\n ((2, 0, 1))))\n self.t = 1\n self.obs = [obs]\n self.action = [torch.FloatTensor(torch.zeros(1, self.action_space))]\n self.reward = [0]\n self.done = [False]\n \n def append(self, \n episode_attrs: Tuple[TensorType]) -> None:\n \"\"\" Appends episode attribute to the list.\"\"\"\n obs, action, reward, done = episode_attrs\n obs = torch.FloatTensor(np.ascontiguousarray(obs.transpose\n ((2, 0, 1))))\n self.t += 1\n self.obs.append(obs)\n self.action.append(action)\n self.reward.append(reward)\n self.done.append(done)\n \n def reset(self, \n obs:TensorType) -> None:\n \"\"\" Resets Episode list of attributes.\"\"\"\n obs = torch.FloatTensor(np.ascontiguousarray(obs.transpose\n ((2, 0, 1))))\n self.t = 1\n self.obs = [obs]\n self.action = [torch.FloatTensor(torch.zeros(1, self.action_space))]\n self.reward = [0]\n self.done = [False]\n \n def todict(self,) -> Dict:\n episode_dict = dict({'count': self.t,\n 'obs': torch.stack(self.obs),\n 'action': torch.cat(self.action),\n 'reward': torch.FloatTensor(self.reward),\n 'done': torch.BoolTensor(self.done)})\n return " ]
[ [ "torch.manual_seed", "numpy.random.seed" ], [ "torch.BoolTensor", "torch.cat", "torch.zeros", "torch.FloatTensor", "torch.stack", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]